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.codedeploy/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/CodeDeployPlugin.java
package com.amazonaws.eclipse.codedeploy; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.ui.IStartup; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.statushandlers.StatusManager; import org.osgi.framework.BundleContext; import com.amazonaws.eclipse.codedeploy.explorer.image.CodeDeployExplorerImages; public class CodeDeployPlugin extends AbstractUIPlugin implements IStartup { public static final String PLUGIN_ID = "com.amazonaws.eclipse.codedeploy"; public static final String DEFAULT_REGION = "us-east-1"; private static CodeDeployPlugin plugin; @Override public void earlyStartup() { } @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } @Override protected ImageRegistry createImageRegistry() { return CodeDeployExplorerImages.createImageRegistry(); } /** * Returns the shared plugin instance. * * @return the shared plugin instance. */ public static CodeDeployPlugin getDefault() { return plugin; } /** * Convenience method for reporting the exception to StatusManager */ public void reportException(String errorMessage, Throwable e) { StatusManager.getManager().handle( new Status(IStatus.ERROR, PLUGIN_ID, errorMessage, e), StatusManager.SHOW | StatusManager.LOG); } /** * Convenience method for logging a debug message at INFO level. */ public void logInfo(String debugMessage) { getLog().log(new Status(Status.INFO, PLUGIN_ID, debugMessage, null)); } public void warn(String message, Throwable e) { getLog().log(new Status(Status.WARNING, PLUGIN_ID, message, e)); } }
7,100
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/ServiceAPIUtils.java
package com.amazonaws.eclipse.codedeploy; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import com.amazonaws.services.codedeploy.AmazonCodeDeploy; import com.amazonaws.services.codedeploy.model.ApplicationInfo; import com.amazonaws.services.codedeploy.model.BatchGetApplicationsRequest; import com.amazonaws.services.codedeploy.model.BatchGetApplicationsResult; import com.amazonaws.services.codedeploy.model.BatchGetDeploymentsRequest; import com.amazonaws.services.codedeploy.model.BatchGetDeploymentsResult; import com.amazonaws.services.codedeploy.model.DeploymentGroupInfo; import com.amazonaws.services.codedeploy.model.DeploymentInfo; import com.amazonaws.services.codedeploy.model.GetDeploymentGroupRequest; import com.amazonaws.services.codedeploy.model.GetDeploymentInstanceRequest; import com.amazonaws.services.codedeploy.model.InstanceSummary; import com.amazonaws.services.codedeploy.model.LifecycleEvent; import com.amazonaws.services.codedeploy.model.ListApplicationsRequest; import com.amazonaws.services.codedeploy.model.ListApplicationsResult; import com.amazonaws.services.codedeploy.model.ListDeploymentConfigsRequest; import com.amazonaws.services.codedeploy.model.ListDeploymentConfigsResult; import com.amazonaws.services.codedeploy.model.ListDeploymentGroupsRequest; import com.amazonaws.services.codedeploy.model.ListDeploymentGroupsResult; import com.amazonaws.services.codedeploy.model.ListDeploymentInstancesRequest; import com.amazonaws.services.codedeploy.model.ListDeploymentInstancesResult; import com.amazonaws.services.codedeploy.model.ListDeploymentsRequest; import com.amazonaws.services.codedeploy.model.ListDeploymentsResult; public class ServiceAPIUtils { public static List<String> getAllApplicationNames(AmazonCodeDeploy client) { List<String> allAppNames = new LinkedList<>(); String nextToken = null; do { ListApplicationsResult result = client.listApplications( new ListApplicationsRequest() .withNextToken(nextToken)); List<String> appNames = result.getApplications(); if (appNames != null) { allAppNames.addAll(appNames); } nextToken = result.getNextToken(); } while (nextToken != null); return allAppNames; } public static List<ApplicationInfo> getAllApplicationInfos(AmazonCodeDeploy client) { List<ApplicationInfo> allAppInfos = new LinkedList<>(); List<String> allAppNames = getAllApplicationNames(client); if (allAppNames != null && !allAppNames.isEmpty()) { BatchGetApplicationsResult result = client.batchGetApplications( new BatchGetApplicationsRequest() .withApplicationNames(allAppNames)); if (result.getApplicationsInfo() != null) { allAppInfos.addAll(result.getApplicationsInfo()); } } return allAppInfos; } public static List<String> getAllDeploymentGroupNames( AmazonCodeDeploy client, String applicationName) { List<String> allDeployGroupNames = new LinkedList<>(); String nextToken = null; do { ListDeploymentGroupsResult result = client.listDeploymentGroups( new ListDeploymentGroupsRequest() .withApplicationName(applicationName) .withNextToken(nextToken)); List<String> deployGroupNames = result.getDeploymentGroups(); if (deployGroupNames != null) { allDeployGroupNames.addAll(deployGroupNames); } nextToken = result.getNextToken(); } while (nextToken != null); return allDeployGroupNames; } public static List<DeploymentGroupInfo> getAllDeploymentGroupInfos( AmazonCodeDeploy client, String applicationName) { List<DeploymentGroupInfo> allDeployGroupInfos = new LinkedList<>(); List<String> allDeployGroupNames = getAllDeploymentGroupNames(client, applicationName); for (String deployGroupName : allDeployGroupNames) { DeploymentGroupInfo group = client.getDeploymentGroup( new GetDeploymentGroupRequest() .withApplicationName(applicationName) .withDeploymentGroupName(deployGroupName)) .getDeploymentGroupInfo(); allDeployGroupInfos.add(group); } return allDeployGroupInfos; } public static List<String> getAllDeploymentConfigNames(AmazonCodeDeploy client) { List<String> allConfigNames = new LinkedList<>(); String nextToken = null; do { ListDeploymentConfigsResult result = client.listDeploymentConfigs( new ListDeploymentConfigsRequest() .withNextToken(nextToken)); List<String> configNames = result.getDeploymentConfigsList(); if (configNames != null) { allConfigNames.addAll(configNames); } nextToken = result.getNextToken(); } while (nextToken != null); return allConfigNames; } public static List<DeploymentInfo> getAllDeployments( AmazonCodeDeploy client, String applicationName, String deploymentGroupName) { List<DeploymentInfo> allDeploymentInfos = new LinkedList<>(); String nextToken = null; do { ListDeploymentsResult result = client.listDeployments( new ListDeploymentsRequest() .withApplicationName(applicationName) .withDeploymentGroupName(deploymentGroupName) .withNextToken(nextToken) ); List<String> deploymentIds = result.getDeployments(); if (deploymentIds != null) { BatchGetDeploymentsResult batchGetResult = client.batchGetDeployments( new BatchGetDeploymentsRequest() .withDeploymentIds(deploymentIds)); if (batchGetResult.getDeploymentsInfo() != null) { allDeploymentInfos.addAll(batchGetResult.getDeploymentsInfo()); } } nextToken = result.getNextToken(); } while (nextToken != null); return allDeploymentInfos; } public static DeploymentInfo getMostRecentDeployment( AmazonCodeDeploy client, String applicationName, String deploymentGroupName) { List<String> deploymentIds = client.listDeployments( new ListDeploymentsRequest() .withApplicationName(applicationName) .withDeploymentGroupName(deploymentGroupName) ).getDeployments(); if (deploymentIds == null || deploymentIds.isEmpty()) { return null; } List<DeploymentInfo> latestDeploymentInfosPage = client.batchGetDeployments( new BatchGetDeploymentsRequest() .withDeploymentIds(deploymentIds) ).getDeploymentsInfo(); if (latestDeploymentInfosPage == null || latestDeploymentInfosPage.isEmpty()) { return null; } // Sort by creation data Collections.sort(latestDeploymentInfosPage, new Comparator<DeploymentInfo>() { @Override public int compare(DeploymentInfo a, DeploymentInfo b) { int a_to_b = a.getCreateTime().compareTo(b.getCreateTime()); // In descending order return - a_to_b; } }); return latestDeploymentInfosPage.get(0); } public static List<InstanceSummary> getAllDeploymentInstances( AmazonCodeDeploy client, String deploymentId) { List<InstanceSummary> allDeploymentInstances = new LinkedList<>(); String nextToken = null; do { ListDeploymentInstancesResult result = client.listDeploymentInstances( new ListDeploymentInstancesRequest() .withDeploymentId(deploymentId) .withNextToken(nextToken) ); List<String> instanceIds = result.getInstancesList(); if (instanceIds != null) { for (String instanceId : instanceIds) { allDeploymentInstances.add(client.getDeploymentInstance( new GetDeploymentInstanceRequest() .withDeploymentId(deploymentId) .withInstanceId(instanceId) ) .getInstanceSummary()); } } nextToken = result.getNextToken(); } while (nextToken != null); return allDeploymentInstances; } public static LifecycleEvent findLifecycleEventByEventName(InstanceSummary instanceSummary, String eventName) { for (LifecycleEvent event : instanceSummary.getLifecycleEvents()) { if (event.getLifecycleEventName().equals(eventName)) { return event; } } throw new RuntimeException(eventName + " event not found in the InstanceSummary."); } }
7,101
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/appspec/PreferenceStoreConstants.java
package com.amazonaws.eclipse.codedeploy.appspec; public class PreferenceStoreConstants { public static final String P_CUSTOM_APPSPEC_TEMPLATE_LOCATIONS = "customAppspecTemplateLocations"; // TODO: what if the path itself contains these characters? public static final String LOCATION_SEPARATOR = "||"; }
7,102
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/appspec/AppspecTemplateRegistry.java
package com.amazonaws.eclipse.codedeploy.appspec; import static com.amazonaws.eclipse.codedeploy.appspec.PreferenceStoreConstants.LOCATION_SEPARATOR; import static com.amazonaws.eclipse.codedeploy.appspec.PreferenceStoreConstants.P_CUSTOM_APPSPEC_TEMPLATE_LOCATIONS; import java.io.File; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import org.eclipse.core.runtime.FileLocator; import org.eclipse.jface.preference.IPreferenceStore; import org.osgi.framework.Bundle; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.appspec.model.AppspecTemplateMetadataModel; import com.amazonaws.util.StringUtils; public class AppspecTemplateRegistry { /** * All the default template metadata files are located inside * {plugin-root}/template-metadata */ private static final String DEFAULT_TEMPLATE_METADATA_BASEDIR = "template-metadata"; private static final AppspecTemplateRegistry INSTANCE = new AppspecTemplateRegistry( CodeDeployPlugin.getDefault().getPreferenceStore()); private final IPreferenceStore prefStore; public static AppspecTemplateRegistry getInstance() { return INSTANCE; } /** * Load all the template metadata files located inside * {plugin-root}/template-metadata */ public List<AppspecTemplateMetadataModel> getDefaultTemplates() { List<AppspecTemplateMetadataModel> models = new LinkedList<>(); try { Bundle bundle = CodeDeployPlugin.getDefault().getBundle(); URL bundleBaseUrl = FileLocator.resolve(bundle.getEntry("/")); File defaultTemplateMetadataDir = new File(bundleBaseUrl.getFile(), DEFAULT_TEMPLATE_METADATA_BASEDIR); for (File metadataFile : defaultTemplateMetadataDir.listFiles()) { try { models.add(AppspecTemplateMetadataModel.loadFromFile(metadataFile, true)); } catch (Exception e) { // log exception and proceed to the next template CodeDeployPlugin.getDefault().warn(String.format( "Failed to load template metadata from %s.", metadataFile.getAbsolutePath()), e); } } return models; } catch (Exception e) { CodeDeployPlugin.getDefault().reportException( "Failed to load default appspec templates.", e); return null; } } public List<AppspecTemplateMetadataModel> getCustomTemplates() { List<AppspecTemplateMetadataModel> models = new LinkedList<>(); String prefValue = prefStore.getString(P_CUSTOM_APPSPEC_TEMPLATE_LOCATIONS); if (prefValue != null && !prefValue.isEmpty()) { String[] locations = prefValue.split(Pattern.quote(LOCATION_SEPARATOR)); for (String location : locations) { File metadataFile = new File(location); try { models.add(AppspecTemplateMetadataModel.loadFromFile(metadataFile, true)); } catch (Exception e) { // log exception and proceed to the next template CodeDeployPlugin.getDefault().warn(String.format( "Failed to load template metadata from %s.", metadataFile.getAbsolutePath()), e); } } } return models; } public Set<String> getAllTemplateNames() { Set<String> allNames = new HashSet<>(); for (AppspecTemplateMetadataModel template : getDefaultTemplates()) { allNames.add(template.getTemplateName()); } for (AppspecTemplateMetadataModel template : getCustomTemplates()) { allNames.add(template.getTemplateName()); } return allNames; } public AppspecTemplateMetadataModel importCustomTemplateMetadata(File metadataFile) { AppspecTemplateMetadataModel newTemplate = AppspecTemplateMetadataModel .loadFromFile(metadataFile, true); // Check template name conflict if (getAllTemplateNames().contains(newTemplate.getTemplateName())) { throw new RuntimeException(String.format( "The \"%s\" template already exists.", newTemplate.getTemplateName())); } String prefValue = prefStore.getString(P_CUSTOM_APPSPEC_TEMPLATE_LOCATIONS); if (prefValue != null && !prefValue.isEmpty()) { List<String> locations = new LinkedList<>( Arrays.asList(prefValue.split(Pattern.quote(LOCATION_SEPARATOR)))); locations.add(metadataFile.getAbsolutePath()); prefStore.setValue( P_CUSTOM_APPSPEC_TEMPLATE_LOCATIONS, StringUtils.join(LOCATION_SEPARATOR, locations.toArray(new String[locations.size()]))); } else { prefStore.setValue( P_CUSTOM_APPSPEC_TEMPLATE_LOCATIONS, metadataFile.getAbsolutePath()); } return newTemplate; } private AppspecTemplateRegistry(IPreferenceStore prefStore) { this.prefStore = prefStore; }; }
7,103
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/appspec
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/appspec/util/JacksonUtils.java
package com.amazonaws.eclipse.codedeploy.appspec.util; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonUtils { public static final ObjectMapper MAPPER = new ObjectMapper(); static { MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); } }
7,104
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/appspec
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/appspec/model/AppspecTemplateMetadataModel.java
package com.amazonaws.eclipse.codedeploy.appspec.model; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import org.eclipse.core.runtime.FileLocator; import org.osgi.framework.Bundle; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.appspec.util.JacksonUtils; import com.amazonaws.protocol.json.SdkJsonGenerator.JsonGenerationException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; public class AppspecTemplateMetadataModel { private final String metadataVersion; private final String templateName; private final String templateDescription; private final String templateBasedir; // Use boxed Boolean so that we can differentiate a non-specified boolean value private final Boolean isCustomTemplate; private final String warFileExportLocationWithinDeploymentArchive; private final boolean useDefaultHttpPortParameter; private final boolean useDefaultContextPathParameter; private final List<AppspecTemplateParameter> parameters; @JsonCreator public AppspecTemplateMetadataModel( @JsonProperty("metadataVersion") String metadataVersion, @JsonProperty("templateName") String templateName, @JsonProperty("templateDescription") String templateDescription, @JsonProperty("templateBasedir") String templateBasedir, @JsonProperty("isCustomTemplate") Boolean isCustomTemplate, @JsonProperty("warFileExportLocationWithinDeploymentArchive") String warFileExportLocationWithinDeploymentArchive, @JsonProperty("useDefaultHttpPortParameter") boolean useDefaultHttpPortParameter, @JsonProperty("useDefaultContextPathParameter") boolean useDefaultContextPathParameter, @JsonProperty("parameters") List<AppspecTemplateParameter> parameters) { this.metadataVersion = metadataVersion; this.templateName = templateName; this.templateDescription = templateDescription; this.templateBasedir = templateBasedir; this.isCustomTemplate = isCustomTemplate; this.warFileExportLocationWithinDeploymentArchive = warFileExportLocationWithinDeploymentArchive; this.useDefaultHttpPortParameter = useDefaultHttpPortParameter; this.useDefaultContextPathParameter = useDefaultContextPathParameter; this.parameters = parameters; } public String getMetadataVersion() { return metadataVersion; } public String getTemplateName() { return templateName; } public String getTemplateDescription() { return templateDescription; } public String getTemplateBasedir() { return templateBasedir; } @JsonIgnore public File getResolvedTemplateBasedir() { if (isCustomTemplate) { return new File(templateBasedir); } else { Bundle bundle = CodeDeployPlugin.getDefault().getBundle(); URL bundleBaseUrl; try { bundleBaseUrl = FileLocator.resolve(bundle.getEntry("/")); } catch (IOException e) { throw new RuntimeException( "Failed to resolve root entry in the CodeDeploy plugin bundle", e); } // Relative to the bundle root return new File(bundleBaseUrl.getFile(), templateBasedir); } } public boolean getIsCustomTemplate() { return isCustomTemplate; } public String getWarFileExportLocationWithinDeploymentArchive() { return warFileExportLocationWithinDeploymentArchive; } public boolean isUseDefaultHttpPortParameter() { return useDefaultHttpPortParameter; } public boolean isUseDefaultContextPathParameter() { return useDefaultContextPathParameter; } public List<AppspecTemplateParameter> getParameters() { return parameters; } /* * Utility functions for loading or outputing the metadata model. */ public static AppspecTemplateMetadataModel loadFromFile(File metadataFile, boolean validateAfterLoaded) { if ( !metadataFile.exists() ) { throw new RuntimeException(String.format( "The template metadata file [%s] doesn't exist.", metadataFile.getAbsolutePath())); } if ( !metadataFile.isFile() ) { throw new RuntimeException(String.format( "The specified location [%s] is not a file.", metadataFile.getAbsolutePath())); } try { AppspecTemplateMetadataModel model = JacksonUtils.MAPPER.readValue(metadataFile, AppspecTemplateMetadataModel.class); if (validateAfterLoaded) { model.validate(); } return model; } catch (JsonParseException e) { throw new RuntimeException( "Failed to parse metadata file at " + metadataFile.getAbsolutePath(), e); } catch (JsonMappingException e) { throw new RuntimeException( "Failed to parse metadata file at " + metadataFile.getAbsolutePath(), e); } catch (IOException e) { throw new RuntimeException( "Failed to read metadata file at " + metadataFile.getAbsolutePath(), e); } } public void writeToFile(File destination) { try { JacksonUtils.MAPPER.writeValue(destination, this); } catch (JsonGenerationException e) { throw new RuntimeException( "Failed to serialize metadata model into JSON string.", e); } catch (JsonMappingException e) { throw new RuntimeException( "Failed to serialize metadata model into JSON string.", e); } catch (IOException e) { throw new RuntimeException( "Failed to write metadata to file " + destination.getAbsolutePath(), e); } } /** * @throw IllegalArgumentException if the template model is not valid */ @JsonIgnore public void validate() { checkRequiredFields(); checkVersion(); checkTemplateBaseDir(); checkTemplateParameters(); } private void checkRequiredFields() { if (metadataVersion == null) throw new IllegalArgumentException("metadataVersion is not specified."); if (templateName == null) throw new IllegalArgumentException("templateName is not specified."); if (templateDescription == null) throw new IllegalArgumentException("templateDescription is not specified."); if (templateBasedir == null) throw new IllegalArgumentException("templateBasedir is not specified."); if (isCustomTemplate == null) throw new IllegalArgumentException("isCustomTemplate is not specified."); if (warFileExportLocationWithinDeploymentArchive == null) throw new IllegalArgumentException("warFileExportLocationWithinDeploymentArchive is not specified."); } private void checkVersion() { if ( !"1.0".equals(metadataVersion) ) throw new IllegalArgumentException("Unsupported metadata version: " + metadataVersion); } private void checkTemplateBaseDir() { checkTemplateBaseDir(getResolvedTemplateBasedir()); } private void checkTemplateBaseDir(File basedir) { if ( !basedir.exists() ) { throw new IllegalArgumentException(String.format( "The template base directory[%s] doesn't exist.", basedir.getAbsolutePath())); } if ( !basedir.isDirectory() ) { throw new IllegalArgumentException(String.format( "The specified location[%s] is not a directory.", basedir.getAbsolutePath())); } File appspecFile = new File(basedir, "appspec.yml"); if ( !appspecFile.exists() || !appspecFile.isFile() ) { throw new IllegalArgumentException(String.format( "The appspec file doesn't exist at the specified location[%s].", appspecFile.getAbsolutePath())); } } private void checkTemplateParameters() { if (parameters != null) { for (AppspecTemplateParameter parameter : parameters) { parameter.validate(); } } } @Override public String toString() { try { return JacksonUtils.MAPPER.writeValueAsString(this); } catch (Exception e) { throw new RuntimeException( "Failed to serialize metadata model into JSON string.", e); } } }
7,105
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/appspec
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/appspec/model/AppspecTemplateParameter.java
package com.amazonaws.eclipse.codedeploy.appspec.model; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public class AppspecTemplateParameter { private final String name; private final ParameterType type; private final String defaultValueAsString; private final String substitutionAnchorText; private final ParameterConstraints constraints; @JsonCreator public AppspecTemplateParameter( @JsonProperty("name") String name, @JsonProperty("type") ParameterType type, @JsonProperty("defaultValueAsString") String defaultValueAsString, @JsonProperty("constraints") ParameterConstraints constraints, @JsonProperty("substitutionAnchorText") String substitutionAnchorText) { this.name = name; this.type = type; this.defaultValueAsString = defaultValueAsString; this.constraints = constraints; this.substitutionAnchorText = substitutionAnchorText; } public String getName() { return name; } public ParameterType getType() { return type; } public String getDefaultValueAsString() { return defaultValueAsString; } public ParameterConstraints getConstraints() { return constraints; } public String getSubstitutionAnchorText() { return substitutionAnchorText; } /** * @throw IllegalArgumentException if the parameter model is not valid */ @JsonIgnore public void validate() { checkRequiredFields(); checkConstraints(); } private void checkRequiredFields() { if (substitutionAnchorText == null) throw new IllegalArgumentException("substitutionAnchorText is not specified for the template parameter."); if (name == null) throw new IllegalArgumentException("name is not specified for parameter " + substitutionAnchorText); if (type == null) throw new IllegalArgumentException("type is not specified for parameter " + substitutionAnchorText); if (defaultValueAsString == null) throw new IllegalArgumentException("defaultValueAsString is not specified for parameter " + substitutionAnchorText); } private void checkConstraints() { if (type == ParameterType.STRING) { if (constraints.getMaxValue() != null || constraints.getMinValue() != null) { throw new IllegalArgumentException( "Invalid constraints for parameter " + substitutionAnchorText + ". minValue or maxValue cannot be set for STRING-type parameter."); } if (constraints.getValidationRegex() != null) { try { Pattern.compile(constraints.getValidationRegex()); } catch (PatternSyntaxException e) { throw new IllegalArgumentException( "Invalid regex constraint for parameter " + substitutionAnchorText, e); } } } else if (type == ParameterType.INTEGER) { if (constraints.getValidationRegex() != null) { throw new IllegalArgumentException( "Invalid constraints for parameter " + substitutionAnchorText + ". validationRegex cannot be set for INTEGER-type parameter."); } if (constraints.getMaxValue() != null && constraints.getMinValue() != null && constraints.getMaxValue() < constraints.getMinValue()) { throw new IllegalArgumentException( "Invalid constraints for parameter " + substitutionAnchorText + ". maxValue cannot be smaller than minValue."); } } } public static class ParameterConstraints { /** For STRING type */ private final String validationRegex; /** For INTEGER type */ private final Integer minValue; private final Integer maxValue; @JsonCreator public ParameterConstraints( @JsonProperty("validationRegex") String validationRegex, @JsonProperty("minValue") Integer minValue, @JsonProperty("maxValue") Integer maxValue) { this.validationRegex = validationRegex; this.minValue = minValue; this.maxValue = maxValue; } public String getValidationRegex() { return validationRegex; } public Integer getMinValue() { return minValue; } public Integer getMaxValue() { return maxValue; } } public enum ParameterType { STRING, INTEGER } }
7,106
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/handler/DeployProjectToCodeDeployHandler.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.codedeploy.deploy.handler; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IProject; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.handlers.HandlerUtil; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.deploy.wizard.DeployProjectToCodeDeployWizard; public class DeployProjectToCodeDeployHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event) .getActivePage().getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection structurredSelection = (IStructuredSelection)selection; Object firstSeleciton = structurredSelection.getFirstElement(); if (firstSeleciton instanceof IProject) { IProject selectedProject = (IProject) firstSeleciton; try { WizardDialog wizardDialog = new WizardDialog( Display.getCurrent().getActiveShell(), new DeployProjectToCodeDeployWizard(selectedProject)); wizardDialog.open(); } catch (Exception e) { CodeDeployPlugin.getDefault().reportException( "Failed to launch deployment wizard.", e); } } else { CodeDeployPlugin.getDefault().logInfo( "Invalid selection: " + firstSeleciton + " is not a project."); } } return null; } }
7,107
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/progress/LifecycleEventDiagnosticsDialog.java
package com.amazonaws.eclipse.codedeploy.deploy.progress; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; 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.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.amazonaws.services.codedeploy.model.Diagnostics; public class LifecycleEventDiagnosticsDialog extends Dialog { private final Diagnostics lifecycleEventDiagnostics; private static final int WIDTH_HINT = 300; public LifecycleEventDiagnosticsDialog(Shell parentShell, Diagnostics lifecycleEventDiagnostics) { super(parentShell); if (lifecycleEventDiagnostics == null) { throw new NullPointerException("lifecycleEventDiagnostics must not be null."); } this.lifecycleEventDiagnostics = lifecycleEventDiagnostics; } /** * To customize the dialog title */ @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("Lifecycle Event Diagnostic Information"); } /** * To customize the dialog button */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, "Close", false); } @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(1, false); container.setLayout(layout); Label label_ErrorCode = new Label(container, SWT.NONE); label_ErrorCode.setText("Error code: " + toUIString(lifecycleEventDiagnostics.getErrorCode())); Label label_ErrorMessage_Title = new Label(container, SWT.NONE); label_ErrorMessage_Title.setText("Error message: "); Text text_ErrorMessage = new Text(container, SWT.BORDER | SWT.WRAP | SWT.READ_ONLY | SWT.V_SCROLL); GridData gridData0 = new GridData(SWT.FILL, SWT.TOP, true, false); gridData0.heightHint = 100; gridData0.widthHint = WIDTH_HINT; text_ErrorMessage.setLayoutData(gridData0); text_ErrorMessage.setText(toUIString(lifecycleEventDiagnostics.getMessage())); Label label_ScriptName = new Label(container, SWT.NONE); label_ScriptName.setText("Script name: " + toUIString(lifecycleEventDiagnostics.getScriptName())); Label label_LogTail_Title = new Label(container, SWT.NONE); label_LogTail_Title.setText("Log tail: "); Text text_LogTail = new Text(container, SWT.BORDER | SWT.WRAP | SWT.READ_ONLY | SWT.V_SCROLL); GridData gridData1 = new GridData(SWT.FILL, SWT.TOP, true, true); gridData1.heightHint = 250; gridData1.widthHint = WIDTH_HINT; text_LogTail.setLayoutData(gridData1); text_LogTail.setText(toUIString(lifecycleEventDiagnostics.getLogTail())); return container; } private static String toUIString(Object object) { return object == null ? "n/a" : object.toString(); } }
7,108
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/progress/DeploymentProgressTrackerDialog.java
package com.amazonaws.eclipse.codedeploy.deploy.progress; import java.util.List; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.ProgressIndicator; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.ServiceAPIUtils; import com.amazonaws.eclipse.codedeploy.explorer.image.CodeDeployExplorerImages; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.services.codedeploy.AmazonCodeDeploy; import com.amazonaws.services.codedeploy.model.DeploymentInfo; import com.amazonaws.services.codedeploy.model.DeploymentStatus; import com.amazonaws.services.codedeploy.model.GetDeploymentInstanceRequest; import com.amazonaws.services.codedeploy.model.GetDeploymentRequest; import com.amazonaws.services.codedeploy.model.InstanceStatus; import com.amazonaws.services.codedeploy.model.InstanceSummary; import com.amazonaws.services.codedeploy.model.LifecycleEvent; import com.amazonaws.services.codedeploy.model.LifecycleEventStatus; public class DeploymentProgressTrackerDialog extends Dialog { private final String deploymentId; private final String deploymentGroupName; private final String applicationName; private final AmazonCodeDeploy client; /** * Used as the direct input for the instance table view */ private InstanceSummary[] instanceSummaries; /* * UI widgets */ private Label titleLabel; private Text latestEventMessageText; private ProgressIndicator progressIndicator; private TableViewer instancesTableViewer; private Label viewDiagnosticLabel; private static final String[] EVENTS = new String[] { "ApplicationStop", "DownloadBundle", "BeforeInstall", "Install", "AfterInstall", "ApplicationStart", "ValidateService" }; private static final int INSTANCE_ID_COL_WIDTH = 150; private static final int EVENT_COL_WIDTH = 120; private static final int INSTANCE_TABLE_VIEWER_HEIGHT_HINT = 200; private static final int REFRESH_INTERVAL_MS = 5 * 1000; public DeploymentProgressTrackerDialog(Shell parentShell, String deploymentId, String deploymentGroupName, String applicationName, Region region) { super(parentShell); this.deploymentId = deploymentId; this.deploymentGroupName = deploymentGroupName; this.applicationName = applicationName; String endpoint = region.getServiceEndpoints() .get(ServiceAbbreviations.CODE_DEPLOY); this.client = AwsToolkitCore.getClientFactory() .getCodeDeployClientByEndpoint(endpoint); } /** * To customize the dialog title */ @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(String.format( "Deploying to %s [%s]", applicationName, deploymentGroupName)); } /** * To customize the dialog button */ @Override protected void createButtonsForButtonBar(Composite parent) { // only create the close button createButton(parent, IDialogConstants.CANCEL_ID, "Close", false); } @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(1, false); layout.marginWidth = 15; layout.marginHeight = 15; container.setLayout(layout); titleLabel = new Label(container, SWT.NONE); titleLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); titleLabel.setText("Waiting deployment to complete..."); titleLabel.setFont(JFaceResources.getBannerFont()); Group deploymentInfoGroup = new Group(container, SWT.NONE); deploymentInfoGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); deploymentInfoGroup.setLayout(new GridLayout(1, false)); GridData labelGridData = new GridData(SWT.FILL, SWT.CENTER, true, false); Label label_Application = new Label(deploymentInfoGroup, SWT.NONE); label_Application.setText("Application Name: " + applicationName); label_Application.setLayoutData(labelGridData); Label label_DeploymentGroup = new Label(deploymentInfoGroup, SWT.NONE); label_DeploymentGroup.setText("Deployment Group Name: " + deploymentGroupName); label_DeploymentGroup.setLayoutData(labelGridData); Label label_DeploymentId = new Label(deploymentInfoGroup, SWT.NONE); label_DeploymentId.setText("Deployment ID: " + deploymentId); label_DeploymentId.setLayoutData(labelGridData); progressIndicator = new ProgressIndicator(container); progressIndicator.beginAnimatedTask(); progressIndicator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); latestEventMessageText = new Text(container, SWT.NONE | SWT.WRAP | SWT.READ_ONLY); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.heightHint = 2 * latestEventMessageText.getLineHeight(); latestEventMessageText.setLayoutData(gridData); latestEventMessageText.setEnabled(false); // gray out the background setItalicFont(latestEventMessageText); createDeploymentInstancesTable(container); loadAndStartUpdatingDeploymentInstancesAsync(); return container; } private void updateTitleLabel(final String message) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { if (!titleLabel.isDisposed()) { titleLabel.setText(message); } } }); } private void updateLatestEventLabel(final String message) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { if (!latestEventMessageText.isDisposed()) { latestEventMessageText.setText(message); } } }); } /** * @return true if the deployment has transitioned into the given status. */ private boolean waitTillDeploymentReachState(DeploymentStatus expectedState) { try { while ( this.getContents() != null && !this.getContents().isDisposed() ) { boolean isFinalStatus = false; DeploymentInfo deploymentInfo = client .getDeployment(new GetDeploymentRequest() .withDeploymentId(deploymentId)) .getDeploymentInfo(); String deploymentStatus = deploymentInfo.getStatus(); if (DeploymentStatus.Created.toString().equals(deploymentStatus) || DeploymentStatus.Queued.toString().equals(deploymentStatus) || DeploymentStatus.InProgress.toString().equals(deploymentStatus)) { updateLatestEventLabel("Deployment status - " + deploymentStatus); } if (DeploymentStatus.Succeeded.toString().equals(deploymentStatus) || DeploymentStatus.Stopped.toString().equals(deploymentStatus) || DeploymentStatus.Failed.toString().equals(deploymentStatus)) { isFinalStatus = true; StringBuilder sb = new StringBuilder("Deployment " + deploymentStatus); if (deploymentInfo.getErrorInformation() != null) { sb.append(String.format( " (Error Code: %s, Error Message: %s)", deploymentInfo.getErrorInformation().getCode(), deploymentInfo.getErrorInformation().getMessage())); } updateLatestEventLabel(sb.toString()); if (DeploymentStatus.Succeeded.toString().equals(deploymentStatus)) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { progressIndicator.done(); updateTitleLabel("Deployment complete"); } }); } else { Display.getDefault().syncExec(new Runnable() { @Override public void run() { progressIndicator.showError(); updateTitleLabel("Deployment didn't finish successfully."); } }); } } // return true if the expected status if (expectedState.toString().equals(deploymentStatus)) { return true; } else if (isFinalStatus) { CodeDeployPlugin.getDefault() .logInfo("Deployment reached final status: " + deploymentStatus); return false; } // Otherwise keep polling try { Thread.sleep(REFRESH_INTERVAL_MS); } catch (InterruptedException e) { CodeDeployPlugin.getDefault() .logInfo("Interrupted when polling deployment status"); return false; } } } catch (Exception e) { CodeDeployPlugin.getDefault().reportException( "Error when polling deployment status.", e); } return false; } private void loadAndStartUpdatingDeploymentInstancesAsync() { new Thread(new Runnable() { @Override public void run() { // A short pause before requesting deployment status try { Thread.sleep(1000); } catch (InterruptedException ignored) { } // Start to load deployment status, and Wait till the deployment // is "InProgress" boolean pollInstances = waitTillDeploymentReachState( DeploymentStatus.InProgress); if (!pollInstances) { updateTitleLabel("Deployment didn't finish successfully."); return; } updateLatestEventLabel("Loading all the deployment instances..."); List<InstanceSummary> instances = ServiceAPIUtils .getAllDeploymentInstances(client, deploymentId); CodeDeployPlugin.getDefault().logInfo( instances.size() + " instances are being deployed."); synchronized (DeploymentProgressTrackerDialog.this) { instanceSummaries = instances.toArray( new InstanceSummary[instances.size()]); Display.getDefault().syncExec(new Runnable() { @Override public void run() { instancesTableViewer.setInput(instanceSummaries); instancesTableViewer.refresh(); if ( !viewDiagnosticLabel.isDisposed() ) { viewDiagnosticLabel.setVisible(true); } } }); } updateLatestEventLabel("Updating deployment lifecycle events..."); updateInstanceLifecycleEvents(); updateLatestEventLabel("All instances have reached final status... " + "Waiting for the deployment to finish..."); waitTillDeploymentReachState(DeploymentStatus.Succeeded); } }).start(); } private void updateInstanceLifecycleEvents() { try { while ( this.getContents() != null && !this.getContents().isDisposed() ) { int pendingInstances = 0; synchronized (DeploymentProgressTrackerDialog.this) { if (instanceSummaries == null) { continue; } for (int i = 0; i < instanceSummaries.length; i++) { InstanceSummary instance = instanceSummaries[i]; if (InstanceStatus.InProgress.toString().equals(instance.getStatus()) || InstanceStatus.Pending.toString().equals(instance.getStatus())) { InstanceSummary latestSummary = client.getDeploymentInstance( new GetDeploymentInstanceRequest() .withDeploymentId(deploymentId) .withInstanceId(instance.getInstanceId())) .getInstanceSummary(); instanceSummaries[i] = latestSummary; pendingInstances++; } } } updateLatestEventLabel(String.format( "Waiting for %d instances to complete...(%d done)", pendingInstances, instanceSummaries.length - pendingInstances)); if (pendingInstances > 0) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { if ( !instancesTableViewer.getTable().isDisposed() ) { instancesTableViewer.refresh(); } } }); } else { // All instances have reached the final states return; } try { Thread.sleep(REFRESH_INTERVAL_MS); } catch (InterruptedException e) { System.err.println("Interrupted when polling " + "lifecycle events from deployment instances."); } } } catch (Exception e) { CodeDeployPlugin.getDefault().reportException( "Error when polling lifecycle events from deployment instances.", e); } } private void createDeploymentInstancesTable(Composite container) { instancesTableViewer = new TableViewer(container, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); GridData tableGridData = new GridData(SWT.FILL, SWT.FILL, true, true); tableGridData.heightHint = INSTANCE_TABLE_VIEWER_HEIGHT_HINT; instancesTableViewer.getTable().setLayoutData(tableGridData); final Table table = instancesTableViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); TableViewerColumn instanceIdColumn = new TableViewerColumn(instancesTableViewer, SWT.CENTER); instanceIdColumn.getColumn().setWidth(INSTANCE_ID_COL_WIDTH); instanceIdColumn.getColumn().setText("Instance ID"); instanceIdColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { InstanceSummary instanceSummary = (InstanceSummary)element; // The service returns the full ARN of the instance String instanceArn = instanceSummary.getInstanceId(); int lastSlashIndex = instanceArn.lastIndexOf("/"); String instanceId = lastSlashIndex == -1 ? instanceArn : instanceArn.substring(lastSlashIndex + 1); return instanceId; } @Override public Font getFont(Object element) { // bold font return JFaceResources.getBannerFont(); } }); for (String eventName : EVENTS) { TableViewerColumn eventColumn = new TableViewerColumn(instancesTableViewer, SWT.CENTER); eventColumn.getColumn().setWidth(EVENT_COL_WIDTH); eventColumn.getColumn().setText(eventName); final String eventName_local = eventName; eventColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { InstanceSummary instanceSummary = (InstanceSummary)element; LifecycleEvent event = ServiceAPIUtils.findLifecycleEventByEventName( instanceSummary, eventName_local); return event.getStatus(); } @Override public Image getImage(Object element) { InstanceSummary instanceSummary = (InstanceSummary)element; LifecycleEvent event = ServiceAPIUtils.findLifecycleEventByEventName( instanceSummary, eventName_local); String statusString = event.getStatus(); if (LifecycleEventStatus.Succeeded.toString().equals(statusString)) { return CodeDeployPlugin.getDefault().getImageRegistry() .get(CodeDeployExplorerImages.IMG_CHECK_ICON); } return null; } @Override public Color getForeground(Object element) { InstanceSummary instanceSummary = (InstanceSummary)element; LifecycleEvent event = ServiceAPIUtils.findLifecycleEventByEventName( instanceSummary, eventName_local); String statusString = event.getStatus(); if (LifecycleEventStatus.Pending.toString().equals(statusString) || LifecycleEventStatus.Unknown.toString().equals(statusString)) { return Display.getCurrent().getSystemColor(SWT.COLOR_GRAY); } if (LifecycleEventStatus.InProgress.toString().equals(statusString)) { return Display.getCurrent().getSystemColor(SWT.COLOR_BLUE); } if (LifecycleEventStatus.Failed.toString().equals(statusString)) { return Display.getCurrent().getSystemColor(SWT.COLOR_RED); } return null; } }); } instancesTableViewer.setContentProvider(ArrayContentProvider.getInstance()); instancesTableViewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { StructuredSelection selection = (StructuredSelection) event.getSelection(); Object element = selection.getFirstElement(); if (element instanceof InstanceSummary) { new InstanceSummaryDetailDialog( getShell(), (InstanceSummary)element) .open(); } } }); viewDiagnosticLabel = new Label(container, SWT.NONE); viewDiagnosticLabel.setText("Double-click instance-ID to view the detailed diagnostic information"); setItalicFont(viewDiagnosticLabel); viewDiagnosticLabel.setVisible(false); } private Font italicFont; private void setItalicFont(Control control) { FontData[] fontData = control.getFont() .getFontData(); for (FontData fd : fontData) { fd.setStyle(SWT.ITALIC); } italicFont = new Font(Display.getDefault(), fontData); control.setFont(italicFont); } @Override public boolean close() { if (italicFont != null) italicFont.dispose(); return super.close(); } }
7,109
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/progress/InstanceSummaryDetailDialog.java
package com.amazonaws.eclipse.codedeploy.deploy.progress; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Shell; import com.amazonaws.services.codedeploy.model.InstanceSummary; import com.amazonaws.services.codedeploy.model.LifecycleEvent; public class InstanceSummaryDetailDialog extends Dialog { private final InstanceSummary instanceSummary; public InstanceSummaryDetailDialog(Shell parentShell, InstanceSummary instanceSummary) { super(parentShell); if (instanceSummary == null) { throw new NullPointerException("instanceSummary must not be null."); } this.instanceSummary = instanceSummary; } /** * To customize the dialog title */ @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("Instance Lifecycle Events"); } /** * To customize the dialog button */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, "Close", false); } @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(1, false); container.setLayout(layout); createControls(container, instanceSummary); return container; } private void createControls(Composite parent, InstanceSummary instanceSummary) { for (LifecycleEvent event : instanceSummary.getLifecycleEvents()) { String eventName = event.getLifecycleEventName(); LifecycleEventUIGroup group = new LifecycleEventUIGroup( parent, SWT.NONE, eventName); group.update(event); } } private static String toUIString(Object object) { return object == null ? "n/a" : object.toString(); } private static class LifecycleEventUIGroup extends Group { private Label label_Status; private Label label_StartTime; private Label label_EndTime; private Link link_Diagnostics; public LifecycleEventUIGroup(Composite parent, int style, String groupName) { super(parent, style); setText(groupName); setFont(JFaceResources.getBannerFont()); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); setLayoutData(gridData); setLayout(new GridLayout(1, false)); label_Status = new Label(this, SWT.NONE); label_StartTime = new Label(this, SWT.NONE); label_EndTime = new Label(this, SWT.NONE); link_Diagnostics = new Link(this, SWT.NONE); link_Diagnostics.setText("<a>View diagnostics</a>"); link_Diagnostics.setEnabled(false); } public void update(final LifecycleEvent event) { label_Status.setText("Status: " + toUIString(event.getStatus())); label_StartTime.setText("Start time: " + toUIString(event.getStartTime())); label_EndTime.setText("End time: " + toUIString(event.getEndTime())); if (event.getDiagnostics() != null) { link_Diagnostics.setEnabled(true); link_Diagnostics.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { new LifecycleEventDiagnosticsDialog( getShell(), event.getDiagnostics()) .open(); } }); } } @Override protected void checkSubclass() { } } }
7,110
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/util/WTPWarUtils.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.codedeploy.deploy.util; import java.io.File; import java.io.IOException; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jst.j2ee.datamodel.properties.IJ2EEComponentExportDataModelProperties; import org.eclipse.jst.j2ee.internal.web.archive.operations.WebComponentExportDataModelProvider; import org.eclipse.wst.common.frameworks.datamodel.DataModelFactory; import org.eclipse.wst.common.frameworks.datamodel.IDataModel; import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation; /** * Utilities for exporting Web Tools Platform Java web application projects to * WAR files. */ public class WTPWarUtils { public static IPath exportProjectToWar(IProject project, IPath directory) { File tempFile; try { tempFile = File.createTempFile("aws-eclipse-", ".war", directory.toFile()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Unable to create web application archive: " + e.getMessage(), e); } return exportProjectToWar(project, directory, tempFile.getName()); } public static IPath exportProjectToWar(IProject project, IPath directory, String fileName) { IDataModel dataModel = DataModelFactory.createDataModel(new WebComponentExportDataModelProvider()); if (directory.toFile().exists() == false) { if (directory.toFile().mkdirs() == false) { throw new RuntimeException("Unable to create temp directory for web application archive."); } } String filename = new File(directory.toFile(), fileName).getAbsolutePath(); dataModel.setProperty(IJ2EEComponentExportDataModelProperties.ARCHIVE_DESTINATION, filename); dataModel.setProperty(IJ2EEComponentExportDataModelProperties.PROJECT_NAME, project.getName()); try { IDataModelOperation operation = dataModel.getDefaultOperation(); operation.execute(new NullProgressMonitor(), null); } catch (ExecutionException e) { // TODO: better error handling e.printStackTrace(); throw new RuntimeException("Unable to create web application archive: " + e.getMessage(), e); } return new Path(filename); } }
7,111
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/util/ZipUtils.java
package com.amazonaws.eclipse.codedeploy.deploy.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; public class ZipUtils { public static void createZipFileOfDirectory(File srcDir, File zipOutput) throws IOException { if ( !srcDir.isDirectory() ) { throw new IllegalArgumentException( srcDir.getAbsolutePath() + " is not a directory!"); } ZipOutputStream zipOutputStream = null; String baseName = srcDir.getAbsolutePath() + File.pathSeparator; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutput)); addDirToZip(srcDir, zipOutputStream, baseName); } finally { IOUtils.closeQuietly(zipOutputStream); } } private static void addDirToZip(File dir, ZipOutputStream zip, String baseName) throws IOException { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { addDirToZip(file, zip, baseName); } else { String entryName = file.getAbsolutePath().substring( baseName.length()); ZipEntry zipEntry = new ZipEntry(entryName); zip.putNextEntry(zipEntry); FileInputStream fileInput = new FileInputStream(file); try { IOUtils.copy(fileInput, zip); zip.closeEntry(); } finally { IOUtils.closeQuietly(fileInput); } } } } }
7,112
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/util/DeployUtils.java
package com.amazonaws.eclipse.codedeploy.deploy.util; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import org.apache.commons.io.FileUtils; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.deploy.wizard.model.DeployProjectToCodeDeployWizardDataModel; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.services.codedeploy.AmazonCodeDeploy; import com.amazonaws.services.codedeploy.model.BundleType; import com.amazonaws.services.codedeploy.model.CreateDeploymentRequest; import com.amazonaws.services.codedeploy.model.CreateDeploymentResult; import com.amazonaws.services.codedeploy.model.RevisionLocation; import com.amazonaws.services.codedeploy.model.RevisionLocationType; import com.amazonaws.services.codedeploy.model.S3Location; import com.amazonaws.services.s3.AmazonS3; public class DeployUtils { /** * @return the deployment ID */ public static String createDeployment( DeployProjectToCodeDeployWizardDataModel dataModel, IProgressMonitor progressMonitor) { CodeDeployPlugin.getDefault().logInfo( "Preparing for deployment: " + dataModel.toString()); /* * (1) Export application archive WAR file */ final IProject project = dataModel.getProject(); String uuid = UUID.randomUUID().toString(); String tempDirName = dataModel.getApplicationName() + "-" + uuid + "-deployment-dir"; String zipFileName = dataModel.getApplicationName() + "-" + uuid + ".zip"; File tempDir = new File( new File(System.getProperty("java.io.tmpdir")), tempDirName); File archiveContentDir = new File( tempDir, "archive-content"); progressMonitor.subTask("Export project to WAR file..."); String warFileRelativePath = dataModel.getTemplateModel() .getWarFileExportLocationWithinDeploymentArchive(); CodeDeployPlugin.getDefault().logInfo( "Preparing to export project [" + project.getName() + "] to a WAR file [" + new File(archiveContentDir, warFileRelativePath).getAbsolutePath() + "]."); File warFile = WTPWarUtils.exportProjectToWar( project, new Path(archiveContentDir.getAbsolutePath()), warFileRelativePath).toFile(); CodeDeployPlugin.getDefault().logInfo( "WAR file created at [" + warFile.getAbsolutePath() + "]"); progressMonitor.worked(10); progressMonitor.subTask("Add app-spec file and all the deployment event hooks..."); try { addAppSpecFileAndEventHooks(archiveContentDir, dataModel); } catch (IOException e) { CodeDeployPlugin.getDefault().reportException( "Error when adding app-spec fild and deployment event hooks.", e); } progressMonitor.worked(5); progressMonitor.subTask("Create the ZIP file including all the deployment artifacts..."); File zipArchive = new File(tempDir, zipFileName); CodeDeployPlugin.getDefault().logInfo( "Preparing to bundle project artifacts into a zip file [" + zipArchive.getAbsolutePath() + "]."); try { ZipUtils.createZipFileOfDirectory(archiveContentDir, zipArchive); } catch (IOException e) { CodeDeployPlugin.getDefault().reportException( "Error when creating zip archive file for the deployment.", e); } CodeDeployPlugin.getDefault().logInfo( "Zip file created at [" + zipArchive.getAbsolutePath() + "]."); progressMonitor.worked(15); /* * (2) Upload to S3 */ String bucketName = dataModel.getBucketName(); String keyName = zipArchive.getName(); AmazonS3 s3Client = AwsToolkitCore.getClientFactory().getS3ClientForBucket(bucketName); progressMonitor.subTask("Upload ZIP file to S3..."); CodeDeployPlugin.getDefault().logInfo( "Uploading zip file to S3 bucket [" + bucketName + "]."); s3Client.putObject(bucketName, keyName, zipArchive); CodeDeployPlugin.getDefault().logInfo( "Upload succeed. [s3://" + bucketName + "/" + keyName + "]"); progressMonitor.worked(30); /* * (3) CreateDeployment */ progressMonitor.subTask("Initiate deployment..."); CodeDeployPlugin.getDefault().logInfo( "Making CreateDeployment API call..."); String endpoint = dataModel.getRegion().getServiceEndpoints() .get(ServiceAbbreviations.CODE_DEPLOY); AmazonCodeDeploy client = AwsToolkitCore.getClientFactory() .getCodeDeployClientByEndpoint(endpoint); CreateDeploymentResult result = client.createDeployment(new CreateDeploymentRequest() .withApplicationName(dataModel.getApplicationName()) .withDeploymentGroupName(dataModel.getDeploymentGroupName()) .withDeploymentConfigName(dataModel.getDeploymentConfigName()) .withIgnoreApplicationStopFailures(dataModel.isIgnoreApplicationStopFailures()) .withRevision(new RevisionLocation() .withRevisionType(RevisionLocationType.S3) .withS3Location(new S3Location() .withBucket(bucketName) .withKey(keyName) .withBundleType(BundleType.Zip) )) .withDescription("Deployment created from AWS Eclipse plugin") ); CodeDeployPlugin.getDefault().logInfo( "Deployment submitted. Deployment ID [" + result.getDeploymentId() + "]"); progressMonitor.worked(10); return result.getDeploymentId(); } private static void addAppSpecFileAndEventHooks(File targetBaseDir, final DeployProjectToCodeDeployWizardDataModel deployDataModel) throws IOException { File templateCopySourceRoot = deployDataModel.getTemplateModel() .getResolvedTemplateBasedir(); copyDirectoryWithTransformationHandler(templateCopySourceRoot, targetBaseDir, new FileTransformationHandler() { @Override public void copyFromFileToFile(File src, File target) throws IOException { String srcContent = FileUtils.readFileToString(src); String transformedContent = substituteUserConfiguration( srcContent, deployDataModel.getTemplateParameterValues()); FileUtils.writeStringToFile(target, transformedContent); } }); } private static String substituteUserConfiguration(String originalContent, Map<String, String> paramAnchorTextAndValues) { for (Entry<String, String> entry : paramAnchorTextAndValues.entrySet()) { String anchorText = entry.getKey(); String value = entry.getValue(); originalContent = originalContent.replace(anchorText, value); } return originalContent; } private static void copyDirectoryWithTransformationHandler(File srcDir, File destDir, FileTransformationHandler handler) throws IOException { if (destDir.exists()) { if (destDir.isDirectory() == false) { throw new IOException("Destination '" + destDir + "' exists but is not a directory"); } } else { if (destDir.mkdirs() == false) { throw new IOException("Destination '" + destDir + "' directory cannot be created"); } } if (destDir.canWrite() == false) { throw new IOException("Destination '" + destDir + "' cannot be written to"); } // recurse File[] files = srcDir.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + srcDir); } for (int i = 0; i < files.length; i++) { File copiedFile = new File(destDir, files[i].getName()); if (files[i].isDirectory()) { copyDirectoryWithTransformationHandler(files[i], copiedFile, handler); } else { handler.copyFromFileToFile(files[i], copiedFile); } } } private interface FileTransformationHandler { void copyFromFileToFile(File src, File target) throws IOException; } }
7,113
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/DeployProjectToCodeDeployWizard.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.codedeploy.deploy.wizard; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.wizard.Wizard; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.deploy.progress.DeploymentProgressTrackerDialog; import com.amazonaws.eclipse.codedeploy.deploy.util.DeployUtils; import com.amazonaws.eclipse.codedeploy.deploy.wizard.model.DeployProjectToCodeDeployWizardDataModel; import com.amazonaws.eclipse.codedeploy.deploy.wizard.page.AppspecTemplateSelectionPage; import com.amazonaws.eclipse.codedeploy.deploy.wizard.page.DeploymentConfigurationPage; import com.amazonaws.eclipse.codedeploy.deploy.wizard.page.DeploymentGroupSelectionPage; import com.amazonaws.eclipse.codedeploy.explorer.CodeDeployContentProvider; public class DeployProjectToCodeDeployWizard extends Wizard { private final DeployProjectToCodeDeployWizardDataModel dataModel; /** * We keep a reference to this page so that we can pull the template * parameter values from it when the user clicks finish. */ private AppspecTemplateSelectionPage appspecTemplateSelectionPage; public DeployProjectToCodeDeployWizard(IProject project) { dataModel = new DeployProjectToCodeDeployWizardDataModel(project); setNeedsProgressMonitor(true); } @Override public void addPages() { addPage(new DeploymentGroupSelectionPage(dataModel)); addPage(new DeploymentConfigurationPage(dataModel)); addPage(appspecTemplateSelectionPage = new AppspecTemplateSelectionPage(dataModel)); } @Override public boolean performFinish() { // Pull the template parameter values from the wizard page dataModel.setTemplateParameterValues( appspecTemplateSelectionPage.getParamValuesForSelectedTemplate()); try { getContainer().run(true, false, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Deploying web project [" + dataModel.getProject().getName() + "] to CodeDeploy", 100); // Initiate deployment (80/100 units) final String deploymentId = DeployUtils.createDeployment(dataModel, monitor); if (CodeDeployContentProvider.getInstance() != null) { CodeDeployContentProvider.getInstance().refresh(); } // Open deployment progress tracker (10/100) monitor.subTask("Open deployment progress tracker..."); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { DeploymentProgressTrackerDialog dialog = new DeploymentProgressTrackerDialog( Display.getDefault().getActiveShell(), deploymentId, dataModel.getDeploymentGroupName(), dataModel.getApplicationName(), dataModel.getRegion()); dialog.open(); } }); monitor.worked(10); monitor.done(); } }); } catch (InvocationTargetException e) { CodeDeployPlugin.getDefault().reportException( "Unexpected error during deployment", e.getCause()); } catch (InterruptedException e) { CodeDeployPlugin.getDefault().reportException( "Unexpected InterruptedException during deployment", e.getCause()); } return true; } }
7,114
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page/WizardPageWithOnEnterHook.java
package com.amazonaws.eclipse.codedeploy.deploy.wizard.page; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.WizardPage; /** * To emulate onEnter event for JFace wizard page. * http://www.eclipse.org/forums/index.php/t/88927/ */ abstract class WizardPageWithOnEnterHook extends WizardPage { protected WizardPageWithOnEnterHook(String pageName) { super(pageName); } protected abstract void onEnterPage(); @Override public final boolean canFlipToNextPage() { return isPageComplete() && getNextPage(false) != null; } @Override public final IWizardPage getNextPage() { return getNextPage(true); } private IWizardPage getNextPage(boolean aboutToShow) { IWizardPage nextPage = super.getNextPage(); if (aboutToShow && (nextPage instanceof WizardPageWithOnEnterHook)) { ((WizardPageWithOnEnterHook) nextPage).onEnterPage(); } return nextPage; } }
7,115
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page/DeploymentGroupSelectionPage.java
package com.amazonaws.eclipse.codedeploy.deploy.wizard.page; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCombo; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newFillingLabel; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLink; import java.util.ArrayList; import java.util.Collections; import java.util.List; 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.databinding.observable.value.WritableValue; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Link; import org.eclipse.ui.statushandlers.StatusManager; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.ServiceAPIUtils; import com.amazonaws.eclipse.codedeploy.UrlConstants; import com.amazonaws.eclipse.codedeploy.deploy.wizard.model.DeployProjectToCodeDeployWizardDataModel; 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.ui.CancelableThread; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.eclipse.databinding.BooleanValidator; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.services.codedeploy.AmazonCodeDeploy; public class DeploymentGroupSelectionPage extends WizardPageWithOnEnterHook{ /* Data model and binding */ private final DeployProjectToCodeDeployWizardDataModel dataModel; private final DataBindingContext bindingContext; private final AggregateValidationStatus aggregateValidationStatus; private IObservableValue applicationSelected = new WritableValue(); private IObservableValue deploymentGroupSelected = new WritableValue(); /* UI widgets */ // Select region private Combo regionCombo; // Select application private Combo applicationNameCombo; private Link applicationSelectionMessageLabel; // Select deployment-group private Combo deploymentGroupNameCombo; private Link deploymentGroupSelectionMessageLabel; /* Other */ private AmazonCodeDeploy codeDeployClient; private LoadApplicationsThread loadApplicationsThread; private LoadDeploymentGroupsThread loadDeploymentGroupsThread; private final WebLinkListener webLinkListener = new WebLinkListener(); /* Constants */ private static final String LOADING = "Loading..."; private static final String NONE_FOUND = "None found"; public DeploymentGroupSelectionPage(DeployProjectToCodeDeployWizardDataModel dataModel) { super("Select the target Application and Deployment Group"); setTitle("Select the target Application and Deployment Group"); setDescription(""); this.dataModel = dataModel; this.bindingContext = new DataBindingContext(); this.aggregateValidationStatus = new AggregateValidationStatus( bindingContext, AggregateValidationStatus.MAX_SEVERITY); initializeValidators(); } @Override public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); createRegionSection(composite); createApplicationSelection(composite); createDeploymentGroupSelection(composite); onRegionChange(); bindControls(); setControl(composite); setPageComplete(false); } @Override public void onEnterPage() { } /* Private interface */ private void initializeValidators() { // Bind the validation status to the wizard page message aggregateValidationStatus.addChangeListener(new IChangeListener() { @Override public void handleChange(ChangeEvent arg0) { Object value = aggregateValidationStatus.getValue(); if (value instanceof IStatus == false) return; IStatus status = (IStatus)value; boolean success = (status.getSeverity() == IStatus.OK); setPageComplete(success); if (success) { setMessage("", IStatus.OK); } else { setMessage(status.getMessage(), IStatus.ERROR); } } }); // Validation status providers bindingContext.addValidationStatusProvider(new ChainValidator<Boolean>( applicationSelected, new BooleanValidator("Please select the application"))); bindingContext.addValidationStatusProvider(new ChainValidator<Boolean>( deploymentGroupSelected, new BooleanValidator("Please select the deployment group"))); } private void bindControls() { ISWTObservableValue applicationNameComboObservable = SWTObservables .observeSelection(applicationNameCombo); bindingContext.bindValue( applicationNameComboObservable, PojoObservables.observeValue( dataModel, DeployProjectToCodeDeployWizardDataModel.APPLICATION_NAME_PROPERTY)); ISWTObservableValue deploymentGroupNameComboObservable = SWTObservables .observeSelection(deploymentGroupNameCombo); bindingContext.bindValue( deploymentGroupNameComboObservable, PojoObservables.observeValue( dataModel, DeployProjectToCodeDeployWizardDataModel.DEPLOYMENT_GROUP_NAME_PROPERTY)); } private void createRegionSection(Composite composite) { Group regionGroup = newGroup(composite, "Select AWS Region"); regionGroup.setLayout(new GridLayout(1, false)); regionCombo = newCombo(regionGroup); for (Region region : RegionUtils.getRegionsForService(ServiceAbbreviations.CODE_DEPLOY)) { regionCombo.add(region.getName()); regionCombo.setData(region.getName(), region); } // Find the default region selection Region selectedRegion = dataModel.getRegion(); if (selectedRegion == null) { if ( RegionUtils.isServiceSupportedInCurrentRegion(ServiceAbbreviations.CODE_DEPLOY) ) { selectedRegion = RegionUtils.getCurrentRegion(); } else { selectedRegion = RegionUtils.getRegion(CodeDeployPlugin.DEFAULT_REGION); } } regionCombo.setText(selectedRegion.getName()); regionCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onRegionChange(); } }); newFillingLabel(regionGroup, "Select the AWS region where your CodeDeploy application was created."); } private void createApplicationSelection(Composite composite) { Group applicationGroup = newGroup(composite, "Select CodeDeploy application:"); applicationGroup.setLayout(new GridLayout(1, false)); applicationNameCombo = newCombo(applicationGroup); applicationNameCombo.setEnabled(false); applicationNameCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onApplicationSelectionChange(); } }); applicationSelectionMessageLabel = newLink(applicationGroup, webLinkListener, "", 1); } private void createDeploymentGroupSelection(Composite composite) { Group deploymentGroupSection = newGroup(composite, "Select CodeDeploy Deployment Group:"); deploymentGroupSection.setLayout(new GridLayout(1, false)); deploymentGroupNameCombo = newCombo(deploymentGroupSection); deploymentGroupNameCombo.setEnabled(false); deploymentGroupSelectionMessageLabel = newLink(deploymentGroupSection, webLinkListener, "", 1); } private void onRegionChange() { Region region = (Region)regionCombo.getData(regionCombo.getText()); String endpoint = region.getServiceEndpoints() .get(ServiceAbbreviations.CODE_DEPLOY); codeDeployClient = AwsToolkitCore.getClientFactory() .getCodeDeployClientByEndpoint(endpoint); dataModel.setRegion(region); refreshApplications(); } private void onApplicationSelectionChange() { if (applicationSelected.getValue().equals(Boolean.TRUE)) { refreshDeploymentGroups(); } } private void refreshApplications() { applicationSelected.setValue(false); if (applicationNameCombo != null) { applicationNameCombo.setItems(new String[] {LOADING}); applicationNameCombo.select(0); } if (applicationSelectionMessageLabel != null) { applicationSelectionMessageLabel.setText(""); } CancelableThread.cancelThread(loadApplicationsThread); loadApplicationsThread = new LoadApplicationsThread(); loadApplicationsThread.start(); } private void refreshDeploymentGroups() { deploymentGroupSelected.setValue(false); if (deploymentGroupNameCombo != null) { deploymentGroupNameCombo.setItems(new String[] {LOADING}); deploymentGroupNameCombo.select(0); } if (deploymentGroupSelectionMessageLabel != null) { deploymentGroupSelectionMessageLabel.setText(""); } CancelableThread.cancelThread(loadDeploymentGroupsThread); loadDeploymentGroupsThread = new LoadDeploymentGroupsThread(); loadDeploymentGroupsThread.start(); } private final class LoadApplicationsThread extends CancelableThread { @Override public void run() { final List<String> appNames = new ArrayList<>(); try { appNames.addAll(ServiceAPIUtils.getAllApplicationNames(codeDeployClient)); Collections.sort(appNames); } catch (Exception e) { CodeDeployPlugin.getDefault().reportException( "Unable to load existing applications.", e); setRunning(false); return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { synchronized (LoadApplicationsThread.this) { if ( !isCanceled() ) { applicationNameCombo.removeAll(); for ( String appName : appNames ) { applicationNameCombo.add(appName); } if ( appNames.size() > 0 ) { applicationNameCombo.setEnabled(true); applicationNameCombo.select(0); applicationSelected.setValue(true); refreshDeploymentGroups(); } else { applicationNameCombo.setEnabled(false); applicationNameCombo.setItems(new String[] { NONE_FOUND}); applicationNameCombo.select(0); applicationSelected.setValue(false); applicationSelectionMessageLabel.setText( "No application is found in this region. " + "Please create a new CodeDeploy application via " + "<a href=\"" + String.format(UrlConstants.CODE_DEPLOY_CONSOLE_URL_FORMAT, dataModel.getRegion().getId()) + "\">AWS Console</a> before making a deployment"); deploymentGroupNameCombo.setEnabled(false); deploymentGroupNameCombo.setItems(new String[0]); deploymentGroupSelected.setValue(false); } // Re-calculate UI layout ((Composite)getControl()).layout(); } } } finally { setRunning(false); } } }); } } private final class LoadDeploymentGroupsThread extends CancelableThread { @Override public void run() { final List<String> deployGroupNames = new ArrayList<>(); try { String appName = dataModel.getApplicationName(); deployGroupNames.addAll(ServiceAPIUtils .getAllDeploymentGroupNames(codeDeployClient, appName)); Collections.sort(deployGroupNames); } catch (Exception e) { Status status = new Status(Status.ERROR, CodeDeployPlugin.PLUGIN_ID, "Unable to load existing deployment groups: " + e.getMessage(), e); StatusManager.getManager().handle(status, StatusManager.SHOW); setRunning(false); return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { synchronized (LoadDeploymentGroupsThread.this) { if ( !isCanceled() ) { deploymentGroupNameCombo.removeAll(); for ( String deployGroupName : deployGroupNames ) { deploymentGroupNameCombo.add(deployGroupName); } if ( deployGroupNames.size() > 0 ) { deploymentGroupNameCombo.select(0); deploymentGroupNameCombo.setEnabled(true); deploymentGroupSelected.setValue(true); } else { deploymentGroupNameCombo.setEnabled(false); deploymentGroupNameCombo.setItems(new String[] { NONE_FOUND}); deploymentGroupNameCombo.select(0); deploymentGroupSelected.setValue(false); deploymentGroupSelectionMessageLabel.setText( "No deployment group is found. " + "Please create a new deployment group via " + "<a href=\"" + String.format(UrlConstants.CODE_DEPLOY_CONSOLE_URL_FORMAT, dataModel.getRegion().getId()) + "\">AWS Console</a> before making a deployment"); } // Re-calculate UI layout ((Composite)getControl()).layout(); } } } finally { setRunning(false); } } }); } } }
7,116
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page/ImportAppspecTemplateMetadataDialog.java
package com.amazonaws.eclipse.codedeploy.deploy.wizard.page; import java.io.File; 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.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.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.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.codedeploy.appspec.AppspecTemplateRegistry; import com.amazonaws.eclipse.codedeploy.appspec.model.AppspecTemplateMetadataModel; public class ImportAppspecTemplateMetadataDialog extends Dialog { private Button importButton; private Button browseButton; private Text filePathTextBox; public ImportAppspecTemplateMetadataDialog(Shell parentShell) { super(parentShell); } /** * To customize the dialog title */ @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("Import Appspec Template Metadata"); } /** * To customize the dialog button */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, "Cacel", false); importButton = createButton(parent, IDialogConstants.CLIENT_ID, "Import", false); importButton.setEnabled(false); importButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { final String filepath = filePathTextBox.getText(); new Job("Importing appspec template metadata") { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask("Load and validate template metadata", IProgressMonitor.UNKNOWN); try { final AppspecTemplateMetadataModel newTemplate = AppspecTemplateRegistry.getInstance() .importCustomTemplateMetadata(new File(filepath)); Display.getDefault().syncExec(new Runnable() { @Override public void run() { String message = String.format( "Template [%s] imported!", newTemplate.getTemplateName()); MessageDialog.openInformation( ImportAppspecTemplateMetadataDialog.this.getShell(), "Import Success", message); } }); } catch (final Exception e) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { String message = "Failed to load template metadata. " + e.getMessage(); if (e.getCause() != null) { message += " ( " + e.getCause().getMessage() + ")"; } MessageDialog.openError( ImportAppspecTemplateMetadataDialog.this.getShell(), "Failed to load template metadata", message); } }); return Status.CANCEL_STATUS; } finally { Display.getDefault().syncExec(new Runnable() { @Override public void run() { ImportAppspecTemplateMetadataDialog.this.close(); } }); } monitor.done(); return Status.OK_STATUS; } }.schedule(); } }); } @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(2, false); container.setLayout(layout); Label label = new Label(container, SWT.NONE); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalSpan = 2; label.setLayoutData(gridData); label.setText("Select the location of the template metadata file to import"); filePathTextBox = new Text(container, SWT.BORDER | SWT.READ_ONLY); filePathTextBox.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); browseButton = new Button(container, SWT.PUSH); GridData rightAlign = new GridData(SWT.RIGHT, SWT.TOP, false, false); rightAlign.widthHint = 100; browseButton.setLayoutData(rightAlign); browseButton.setText("Browse"); browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { FileDialog dialog = new FileDialog( ImportAppspecTemplateMetadataDialog.this.getShell(), SWT.OPEN); String filePath = dialog.open(); if (filePath != null) { filePathTextBox.setText(filePath); importButton.setEnabled(true); } } }); return container; } }
7,117
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page/AppspecTemplateSelectionPage.java
package com.amazonaws.eclipse.codedeploy.deploy.wizard.page; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StackLayout; 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.Display; import org.eclipse.swt.widgets.Label; import com.amazonaws.eclipse.codedeploy.appspec.AppspecTemplateRegistry; import com.amazonaws.eclipse.codedeploy.appspec.model.AppspecTemplateMetadataModel; import com.amazonaws.eclipse.codedeploy.deploy.wizard.model.DeployProjectToCodeDeployWizardDataModel; public class AppspecTemplateSelectionPage extends WizardPage { /* Data model */ private final DeployProjectToCodeDeployWizardDataModel dataModel; /** * For fast look-up when switching the top control */ private final Map<AppspecTemplateMetadataModel, AppspecTemplateConfigComposite> templateConfigCompositeMap = new HashMap<>(); /* UI widgets */ private ComboViewer appspecTemplateSelectionCombo; private Composite stackArea; private AppspecTemplateConfigComposite selectedTemplateComposite; /** * The validation status listener to be registered to the template config UI * composite that is currently shown in the page. */ private final IChangeListener selectedTemplateConfigValidationStatusListener = new IChangeListener() { @Override public void handleChange(ChangeEvent event) { Object observable = event.getObservable(); if (observable instanceof AggregateValidationStatus == false) return; AggregateValidationStatus statusObservable = (AggregateValidationStatus)observable; Object statusObservableValue = statusObservable.getValue(); if (statusObservableValue instanceof IStatus == false) return; IStatus status = (IStatus)statusObservableValue; boolean success = (status.getSeverity() == IStatus.OK); setPageComplete(success); if (success) { setMessage("", IStatus.OK); } else { setMessage(status.getMessage(), IStatus.ERROR); } } }; public AppspecTemplateSelectionPage(DeployProjectToCodeDeployWizardDataModel dataModel) { super("Appspec Template Configuration"); setTitle("Appspec Template Configuration"); setDescription(""); this.dataModel = dataModel; } public Map<String, String> getParamValuesForSelectedTemplate() { if (selectedTemplateComposite != null) { return selectedTemplateComposite.getAllParameterValues(); } return Collections.emptyMap(); } @Override public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(3, false)); List<AppspecTemplateMetadataModel> allModels = AppspecTemplateRegistry.getInstance().getDefaultTemplates(); allModels.addAll(AppspecTemplateRegistry.getInstance().getCustomTemplates()); createAppspecTemplateSelection(composite, allModels); stackArea = new Composite(composite, SWT.NONE); GridData stackAreaLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); stackAreaLayoutData.horizontalSpan = 3; stackArea.setLayoutData(stackAreaLayoutData); stackArea.setLayout(new StackLayout()); createStackedTemplateConfigComposites(stackArea, allModels); AppspecTemplateMetadataModel initSelection = allModels.get(0); appspecTemplateSelectionCombo.setSelection( new StructuredSelection(initSelection), true); setControl(composite); setPageComplete(true); } private void createAppspecTemplateSelection( Composite parent, List<AppspecTemplateMetadataModel> allModels) { new Label(parent, SWT.READ_ONLY).setText("Appspec template: "); appspecTemplateSelectionCombo = new ComboViewer(parent, SWT.DROP_DOWN | SWT.READ_ONLY); appspecTemplateSelectionCombo.getCombo().setLayoutData( new GridData(SWT.FILL, SWT.CENTER, true, false)); appspecTemplateSelectionCombo.setContentProvider(ArrayContentProvider.getInstance()); appspecTemplateSelectionCombo.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { if (element instanceof AppspecTemplateMetadataModel) { AppspecTemplateMetadataModel model = (AppspecTemplateMetadataModel) element; return model.getTemplateName(); } return super.getText(element); } }); appspecTemplateSelectionCombo.setInput(allModels); appspecTemplateSelectionCombo .addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event .getSelection(); Object selectedObject = selection.getFirstElement(); if (selectedObject instanceof AppspecTemplateMetadataModel) { AppspecTemplateMetadataModel model = (AppspecTemplateMetadataModel) selectedObject; onTemplateSelectionChanged(model); } } }); Button importTemplateBtn = new Button(parent, SWT.PUSH); importTemplateBtn.setText("Import new template"); importTemplateBtn.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); importTemplateBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { ImportAppspecTemplateMetadataDialog importDialog = new ImportAppspecTemplateMetadataDialog( Display.getCurrent().getActiveShell()); int returnCode = importDialog.open(); if (returnCode != IDialogConstants.CANCEL_ID) { selectImportedTemplate(); } } }); } @SuppressWarnings("unchecked") private void selectImportedTemplate() { Set<String> existingTemplateNames = new HashSet<>(); for (AppspecTemplateMetadataModel template : templateConfigCompositeMap.keySet()) { existingTemplateNames.add(template.getTemplateName()); } // Now re-load from the registry and find the new template model for (AppspecTemplateMetadataModel template : AppspecTemplateRegistry .getInstance().getCustomTemplates()) { if ( !existingTemplateNames.contains(template.getTemplateName()) ) { AppspecTemplateMetadataModel newTemplate = template; ((List<AppspecTemplateMetadataModel>) appspecTemplateSelectionCombo .getInput()).add(newTemplate); AppspecTemplateConfigComposite newTemplateComposite = new AppspecTemplateConfigComposite( stackArea, SWT.NONE, newTemplate); templateConfigCompositeMap.put(newTemplate, newTemplateComposite); appspecTemplateSelectionCombo.refresh(); appspecTemplateSelectionCombo.setSelection( new StructuredSelection(newTemplate), true); return; } } } private void createStackedTemplateConfigComposites( Composite parent, List<AppspecTemplateMetadataModel> allModels) { for (AppspecTemplateMetadataModel templateModel : allModels) { AppspecTemplateConfigComposite templateConfigComposite = new AppspecTemplateConfigComposite( parent, SWT.NONE, templateModel); // put it into the look-up hashmap templateConfigCompositeMap.put(templateModel, templateConfigComposite); } } private void onTemplateSelectionChanged(AppspecTemplateMetadataModel model) { if (selectedTemplateComposite != null) { selectedTemplateComposite.removeValidationStatusChangeListener(); } AppspecTemplateConfigComposite compositeToShow = templateConfigCompositeMap.get(model); if (compositeToShow != null) { StackLayout stackLayout = (StackLayout) stackArea.getLayout(); stackLayout.topControl = compositeToShow; compositeToShow.setValidationStatusChangeListener(selectedTemplateConfigValidationStatusListener); compositeToShow.updateValidationStatus(); stackArea.layout(); selectedTemplateComposite = compositeToShow; dataModel.setTemplateModel(compositeToShow.getTemplateModel()); } } }
7,118
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page/DeploymentConfigurationPage.java
package com.amazonaws.eclipse.codedeploy.deploy.wizard.page; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCheckbox; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCombo; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLink; import java.util.LinkedList; import java.util.List; 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.databinding.observable.value.WritableValue; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Link; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.ServiceAPIUtils; import com.amazonaws.eclipse.codedeploy.UrlConstants; import com.amazonaws.eclipse.codedeploy.deploy.wizard.model.DeployProjectToCodeDeployWizardDataModel; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.databinding.BooleanValidator; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.services.codedeploy.AmazonCodeDeploy; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.Bucket; public class DeploymentConfigurationPage extends WizardPageWithOnEnterHook { /* Data model */ private final DeployProjectToCodeDeployWizardDataModel dataModel; private final DataBindingContext bindingContext; private final AggregateValidationStatus aggregateValidationStatus; private IObservableValue deploymentConfigSelected = new WritableValue(); private IObservableValue bucketNameSelected = new WritableValue(); /* UI widgets */ // Select deployment config private Combo deploymentConfigCombo; // Select S3 bucket private Combo bucketNameCombo; private Link bucketNameSelectionMessageLabel; // ignoreApplicationStopFailures private Button ignoreApplicationStopFailuresCheckBox; /* Constants */ private static final String LOADING = "Loading..."; private static final String NONE_FOUND = "None found"; public DeploymentConfigurationPage(DeployProjectToCodeDeployWizardDataModel dataModel) { super("Deployment Configuration"); setTitle("Deployment Configuration"); setDescription(""); this.dataModel = dataModel; this.bindingContext = new DataBindingContext(); this.aggregateValidationStatus = new AggregateValidationStatus( bindingContext, AggregateValidationStatus.MAX_SEVERITY); initializeValidators(); } @Override public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); createDeploymentConfigSelection(composite); createS3BucketSelection(composite); bindControls(); setControl(composite); setPageComplete(false); } @Override public void onEnterPage() { loadDeploymentConfigsAsync(); loadS3BucketsAsync(); } /* Private interface */ private void initializeValidators() { // Bind the validation status to the wizard page message aggregateValidationStatus.addChangeListener(new IChangeListener() { @Override public void handleChange(ChangeEvent arg0) { Object value = aggregateValidationStatus.getValue(); if (value instanceof IStatus == false) return; IStatus status = (IStatus)value; boolean success = (status.getSeverity() == IStatus.OK); setPageComplete(success); if (success) { setMessage("", IStatus.OK); } else { setMessage(status.getMessage(), IStatus.ERROR); } } }); // Validation status providers bindingContext.addValidationStatusProvider(new ChainValidator<Boolean>( deploymentConfigSelected, new BooleanValidator("Please select the deployment config"))); bindingContext.addValidationStatusProvider(new ChainValidator<Boolean>( bucketNameSelected, new BooleanValidator("Please select the S3 bucket name"))); } private void bindControls() { ISWTObservableValue deploymentConfigComboObservable = SWTObservables .observeSelection(deploymentConfigCombo); bindingContext.bindValue( deploymentConfigComboObservable, PojoObservables.observeValue( dataModel, DeployProjectToCodeDeployWizardDataModel.DEPLOYMENT_CONFIG_NAME_PROPERTY)); ISWTObservableValue bucketNameComboObservable = SWTObservables .observeSelection(bucketNameCombo); bindingContext.bindValue( bucketNameComboObservable, PojoObservables.observeValue( dataModel, DeployProjectToCodeDeployWizardDataModel.BUCKET_NAME_PROPERTY)); ISWTObservableValue ignoreApplicationStopFailuresCheckBoxObservable = SWTObservables .observeSelection(ignoreApplicationStopFailuresCheckBox); bindingContext.bindValue( ignoreApplicationStopFailuresCheckBoxObservable, PojoObservables.observeValue( dataModel, DeployProjectToCodeDeployWizardDataModel.IGNORE_APPLICATION_STOP_FAILURES_PROPERTY)); } private void createDeploymentConfigSelection(Composite composite) { Group deploymentConfigGroup = newGroup(composite, "Select CodeDeploy deployment config:"); deploymentConfigGroup.setLayout(new GridLayout(1, false)); deploymentConfigCombo = newCombo(deploymentConfigGroup); deploymentConfigCombo.setEnabled(false); deploymentConfigSelected.setValue(false); newLink(deploymentConfigGroup, UrlConstants.webLinkListener, "<a href=\"" + "http://docs.aws.amazon.com/codedeploy/latest/userguide/how-to-create-deployment-configuration.html" + "\">Create new deployment configuration.</a>", 1); ignoreApplicationStopFailuresCheckBox = newCheckbox(deploymentConfigGroup, "Ignore ApplicationStop step failures.", 1); } private void loadDeploymentConfigsAsync() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { deploymentConfigCombo.setItems(new String[] {LOADING}); deploymentConfigCombo.select(0); } }); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { String endpoint = dataModel.getRegion().getServiceEndpoints() .get(ServiceAbbreviations.CODE_DEPLOY); AmazonCodeDeploy client = AwsToolkitCore.getClientFactory() .getCodeDeployClientByEndpoint(endpoint); List<String> configNames = ServiceAPIUtils.getAllDeploymentConfigNames(client); if (configNames.isEmpty()) { deploymentConfigCombo.setItems(new String[] {NONE_FOUND}); deploymentConfigSelected.setValue(false); } else { deploymentConfigCombo.setItems(configNames.toArray(new String[configNames.size()])); deploymentConfigCombo.select(0); deploymentConfigCombo.setEnabled(true); deploymentConfigSelected.setValue(true); } } catch (Exception e) { CodeDeployPlugin.getDefault().reportException( "Failed to load deployment configs.", e); } } }); } private void createS3BucketSelection(Composite composite) { Group bucketGroup = newGroup(composite, "Select S3 bucket name:"); bucketGroup.setLayout(new GridLayout(1, false)); bucketNameCombo = newCombo(bucketGroup); bucketNameCombo.setEnabled(false); bucketNameSelected.setValue(false); bucketNameSelectionMessageLabel = newLink(bucketGroup, UrlConstants.webLinkListener, "The S3 bucket should be located at the same region " + "as the target Amazon EC2 instances. " + "For more information, see " + "<a href=\"" + "http://docs.aws.amazon.com/codedeploy/latest/userguide/how-to-push-revision.html" + "\">AWS CodeDeploy User Guide</a>.", 1); setItalicFont(bucketNameSelectionMessageLabel); } private void loadS3BucketsAsync() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { bucketNameCombo.setItems(new String[] {LOADING}); bucketNameCombo.select(0); } }); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { AmazonS3 client = AwsToolkitCore.getClientFactory().getS3Client(); List<Bucket> allBuckets = client.listBuckets(); if (allBuckets.isEmpty()) { bucketNameCombo.setItems(new String[] {NONE_FOUND}); bucketNameSelectionMessageLabel.setText( "No S3 bucket is found. " + "Please create one before making a deployment"); // Re-calculate UI layout ((Composite)getControl()).layout(); bucketNameSelected.setValue(false); } else { List<String> allBucketNames = new LinkedList<>(); for (Bucket bucket : allBuckets) { allBucketNames.add(bucket.getName()); } bucketNameCombo.setItems(allBucketNames.toArray(new String[allBucketNames.size()])); bucketNameCombo.select(0); bucketNameCombo.setEnabled(true); bucketNameSelected.setValue(true); } } catch (Exception e) { CodeDeployPlugin.getDefault().reportException( "Failed to load S3 buckets.", e); } } }); } private Font italicFont; private void setItalicFont(Control control) { FontData[] fontData = control.getFont() .getFontData(); for (FontData fd : fontData) { fd.setStyle(SWT.ITALIC); } italicFont = new Font(Display.getDefault(), fontData); control.setFont(italicFont); } @Override public void dispose() { if (italicFont != null) italicFont.dispose(); super.dispose(); } }
7,119
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page/AppspecTemplateConfigComposite.java
package com.amazonaws.eclipse.codedeploy.deploy.wizard.page; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newControlDecoration; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newFillingLabel; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLabel; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newRadioButton; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newText; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.codedeploy.appspec.model.AppspecTemplateMetadataModel; import com.amazonaws.eclipse.codedeploy.appspec.model.AppspecTemplateParameter; import com.amazonaws.eclipse.codedeploy.deploy.wizard.page.validator.ContextPathValidator; import com.amazonaws.eclipse.codedeploy.deploy.wizard.page.validator.GenericTemplateParameterValidator; import com.amazonaws.eclipse.codedeploy.deploy.wizard.page.validator.ServerHttpPortValidator; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.DecorationChangeListener; /** * The UI composite for displaying the configuration options for a specific * appspec template. The composites for all the available templates are * stacked onto the same stack-layout area. */ class AppspecTemplateConfigComposite extends Composite { private static final String CONTEXT_PATH_ANCHOR_TEXT = "##CONTEXT_PATH##"; private static final String HTTP_PORT_ANCHOR_TEXT = "##HTTP_PORT##"; private static final String DEPLOY_TO_ROOT_ANCHOR_TEXT = "##DEPLOY_TO_ROOT##"; private static final String CONTEXT_PATH_DEFAULT = "application"; private static final String HTTP_PORT_DEFAULT = "8080"; /* Data model */ private final AppspecTemplateMetadataModel templateModel; private final DataBindingContext bindingContext; private final AggregateValidationStatus aggregateValidationStatus; /* * Special UI widgets for HTTP port and context-path configuration */ private Label serverUrlPreviewLabel; private ISWTObservableValue deployToContextPathRadioButtonObservable; private Text contextPathText; private ISWTObservableValue contextPathTextObservable; private Text httpPortText; private ISWTObservableValue httpPortTextObservable; /** * UI widgets for generic parameters */ private final List<ParameterInputGroup> parameterInputGroups = new LinkedList<>(); /** * @see #setValidationStatusChangeListener(IChangeListener) * @see #removeValidationStatusChangeListener() */ private IChangeListener validationStatusChangeListener; public AppspecTemplateConfigComposite(Composite parent, int style, AppspecTemplateMetadataModel templateModel) { super(parent, style); this.templateModel = templateModel; this.bindingContext = new DataBindingContext(); this.aggregateValidationStatus = new AggregateValidationStatus( bindingContext, AggregateValidationStatus.MAX_SEVERITY); setLayout(new GridLayout(2, false)); createControls(this); } public AppspecTemplateMetadataModel getTemplateModel() { return templateModel; } /** * Set listener that will be notified whenever the validation status of this * composite is updated. This method removes the listener (if any) that is * currently registered to this composite - only one listener instance is * allowed at a time. */ public synchronized void setValidationStatusChangeListener(IChangeListener listener) { removeValidationStatusChangeListener(); validationStatusChangeListener = listener; aggregateValidationStatus.addChangeListener(listener); } /** * @see #setValidationStatusChangeListener(IChangeListener) */ public synchronized void removeValidationStatusChangeListener() { if (validationStatusChangeListener != null) { aggregateValidationStatus.removeChangeListener(validationStatusChangeListener); validationStatusChangeListener = null; } } public void updateValidationStatus() { Iterator<?> iterator = bindingContext.getBindings().iterator(); while (iterator.hasNext()) { Binding binding = (Binding)iterator.next(); binding.updateTargetToModel(); } } /** * @return a map of all the template parameter values, keyed by the anchor * text of each parameter. */ public Map<String, String> getAllParameterValues() { Map<String, String> values = new HashMap<>(); if (templateModel.isUseDefaultContextPathParameter()) { values.put(DEPLOY_TO_ROOT_ANCHOR_TEXT, (Boolean)deployToContextPathRadioButtonObservable.getValue() ? "false" : "true"); values.put(CONTEXT_PATH_ANCHOR_TEXT, (String)contextPathTextObservable.getValue()); } if (templateModel.isUseDefaultHttpPortParameter()) { values.put(HTTP_PORT_ANCHOR_TEXT, (String)httpPortTextObservable.getValue()); } for (ParameterInputGroup genericParamInput : parameterInputGroups) { values.put( genericParamInput.getParameterModel().getSubstitutionAnchorText(), genericParamInput.getParameterValue()); } return values; } private void createControls(Composite parent) { Label descriptionLabel = new Label(parent, SWT.NONE); setItalicFont(descriptionLabel); descriptionLabel.setText( toUIString(templateModel.getTemplateDescription())); if (templateModel.isUseDefaultContextPathParameter() || templateModel.isUseDefaultHttpPortParameter()) { createServerUrlPreviewLabel(parent); } if (templateModel.isUseDefaultContextPathParameter()) { createContextPathConfigurationSection(parent); } if (templateModel.isUseDefaultHttpPortParameter()) { createHttpPortConfigurationSection(parent); } if (templateModel.getParameters() != null) { for (AppspecTemplateParameter parameter : templateModel.getParameters()) { ParameterInputGroup parameterInputGroup = new ParameterInputGroup( parent, parameter, bindingContext); parameterInputGroups.add(parameterInputGroup); } } } private static String toUIString(String str) { return str == null ? "n/a" : str; } private void createServerUrlPreviewLabel(Composite composite) { Group group = newGroup(composite, "", 2); group.setLayout(new GridLayout(2, false)); newLabel(group, "Server URL:"); serverUrlPreviewLabel = newFillingLabel(group, String.format("http://{ec2-public-dns}:%s/", HTTP_PORT_DEFAULT)); setBoldFont(serverUrlPreviewLabel); Label label = newFillingLabel(group, "Your application will be available " + "via this endpoint after the deployment.", 2); setItalicFont(label); } private void refreshServerUrlPreviewLabel() { boolean useContextPath = (Boolean) deployToContextPathRadioButtonObservable .getValue(); String contextPath = contextPathText.getText(); String httpPort = httpPortText.getText(); serverUrlPreviewLabel.setText( useContextPath ? String.format("http://{ec2-public-dns}:%s/%s/", httpPort, contextPath) : String.format("http://{ec2-public-dns}:%s/", httpPort) ); } private void createContextPathConfigurationSection(Composite composite) { Group group = newGroup(composite, "", 2); group.setLayout(new GridLayout(2, false)); newRadioButton(group, "Deploy application to server root", 2, true, new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { contextPathText.setEnabled(false); updateValidationStatus(); refreshServerUrlPreviewLabel(); } } ); Button deployToContextPathRadioButton = newRadioButton(group, "Deploy application to context path", 1, false, new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { contextPathText.setEnabled(true); updateValidationStatus(); refreshServerUrlPreviewLabel(); } } ); deployToContextPathRadioButtonObservable = SWTObservables .observeSelection(deployToContextPathRadioButton); contextPathText = newText(group); contextPathText.setEnabled(false); contextPathText.setText(CONTEXT_PATH_DEFAULT); contextPathTextObservable = SWTObservables.observeText(contextPathText, SWT.Modify); bindingContext.bindValue(contextPathTextObservable, contextPathTextObservable); ChainValidator<String> contextPathValidationProvider = new ChainValidator<>( contextPathTextObservable, deployToContextPathRadioButtonObservable, //enabler new ContextPathValidator("Invalid context path.")); bindingContext.addValidationStatusProvider(contextPathValidationProvider); ControlDecoration contextPathTextDecoration = newControlDecoration( contextPathText, "Enter a valid context path for the application."); new DecorationChangeListener( contextPathTextDecoration, contextPathValidationProvider.getValidationStatus()); contextPathText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { refreshServerUrlPreviewLabel(); } }); } private void createHttpPortConfigurationSection(Composite composite) { Group group = newGroup(composite, "", 2); group.setLayout(new GridLayout(2, false)); Label nameLabel = newLabel(group, "Application server HTTP port:"); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); httpPortText = newText(group); httpPortText.setText(HTTP_PORT_DEFAULT); httpPortTextObservable = SWTObservables.observeText(httpPortText, SWT.Modify); bindingContext.bindValue(httpPortTextObservable, httpPortTextObservable); ChainValidator<String> httpPortValidationProvider = new ChainValidator<>( httpPortTextObservable, new ServerHttpPortValidator("Invalid HTTP port.")); bindingContext.addValidationStatusProvider(httpPortValidationProvider); ControlDecoration httpPortTextDecoration = newControlDecoration( httpPortText, "Enter a valid HTTP port for the Tomcat server."); new DecorationChangeListener( httpPortTextDecoration, httpPortValidationProvider.getValidationStatus()); httpPortText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { refreshServerUrlPreviewLabel(); } }); Label httpPortLabel = newFillingLabel(group, "You might need to setup authbind in order to " + "allow servlet container to listen on priviliged ports (0 - 1023).", 2); setItalicFont(httpPortLabel); } private static class ParameterInputGroup extends Group { private final AppspecTemplateParameter parameter; private final DataBindingContext bindingContext; private Text valueInputText; private ControlDecoration valueInputTextDecoration; private ISWTObservableValue valueInputTextObservable; public ParameterInputGroup(Composite parent, AppspecTemplateParameter parameter, DataBindingContext bindingContext) { super(parent, SWT.NONE); if (parameter == null) { throw new NullPointerException("parameter must not be null."); } if (bindingContext == null) { throw new NullPointerException("bindingContext must not be null."); } this.parameter = parameter; this.bindingContext = bindingContext; createControls(parent); } public AppspecTemplateParameter getParameterModel() { return parameter; } public String getParameterValue() { return (String)valueInputTextObservable.getValue(); } private void createControls(Composite composite) { GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalSpan = 2; this.setLayoutData(gridData); this.setLayout(new GridLayout(2, false)); this.setText(parameter.getName()); Label nameLabel = newLabel(this, parameter.getSubstitutionAnchorText()); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); valueInputText = newText(this); valueInputText.setText(parameter.getDefaultValueAsString()); valueInputTextObservable = SWTObservables.observeText(valueInputText, SWT.Modify); bindingContext.bindValue(valueInputTextObservable, valueInputTextObservable); ChainValidator<String> paramValidationStatusProvider = new ChainValidator<>( valueInputTextObservable, new GenericTemplateParameterValidator(parameter)); bindingContext.addValidationStatusProvider(paramValidationStatusProvider); valueInputTextDecoration = newControlDecoration( valueInputText, String.format("Invalid value for parameter %s (%s).", parameter.getSubstitutionAnchorText(), parameter.getName())); new DecorationChangeListener( valueInputTextDecoration, paramValidationStatusProvider.getValidationStatus()); } @Override protected void checkSubclass() {} } /* * Font resources */ private Font italicFont; private Font boldFont; private void setItalicFont(Control control) { FontData[] fontData = control.getFont() .getFontData(); for (FontData fd : fontData) { fd.setStyle(SWT.ITALIC); } italicFont = new Font(Display.getDefault(), fontData); control.setFont(italicFont); } private void setBoldFont(Control control) { FontData[] fontData = control.getFont() .getFontData(); for (FontData fd : fontData) { fd.setStyle(SWT.BOLD); } boldFont = new Font(Display.getDefault(), fontData); control.setFont(boldFont); } @Override public void dispose() { if (italicFont != null) italicFont.dispose(); if (boldFont != null) boldFont.dispose(); super.dispose(); } }
7,120
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page/validator/GenericTemplateParameterValidator.java
package com.amazonaws.eclipse.codedeploy.deploy.wizard.page.validator; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import com.amazonaws.eclipse.codedeploy.appspec.model.AppspecTemplateParameter; import com.amazonaws.eclipse.codedeploy.appspec.model.AppspecTemplateParameter.ParameterConstraints; import com.amazonaws.eclipse.codedeploy.appspec.model.AppspecTemplateParameter.ParameterType; public class GenericTemplateParameterValidator implements IValidator { private final AppspecTemplateParameter parameterModel; public GenericTemplateParameterValidator(AppspecTemplateParameter parameterModel) { this.parameterModel = parameterModel; } public AppspecTemplateParameter getParameterModel() { return parameterModel; } @Override public IStatus validate(Object value) { String input = (String)value; if (input == null) { return error("value must not be null."); } ParameterConstraints constraints = parameterModel.getConstraints(); if (parameterModel.getType() == ParameterType.STRING) { String stringRegex = constraints.getValidationRegex(); if (stringRegex != null && !input.matches(stringRegex)) { return error("value doesn't match regex \"" + stringRegex + "\""); } } else if (parameterModel.getType() == ParameterType.INTEGER) { try { int intValue = Integer.parseInt(input.trim()); if (constraints.getMinValue() != null && intValue < constraints.getMinValue()) { return error("minimum is " + constraints.getMinValue()); } if (constraints.getMaxValue() != null && intValue > constraints.getMaxValue()) { return error("maximum is " + constraints.getMaxValue()); } } catch (NumberFormatException e) { return error("a number is expected"); } } return ValidationStatus.ok(); } private IStatus error(String message) { return ValidationStatus.error(String.format("Invalid value for %s (%s)", parameterModel.getSubstitutionAnchorText(), message)); } }
7,121
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page/validator/ServerHttpPortValidator.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.codedeploy.deploy.wizard.page.validator; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; public class ServerHttpPortValidator implements IValidator { public String message; public ServerHttpPortValidator(String message) { this.message = message; } @Override public IStatus validate(Object value) { String s = (String)value; if (s == null || s.trim().length() == 0) { return ValidationStatus.error(message); } try { int port = Integer.parseInt(s.trim()); if (port < 0 || port > 65535) { return ValidationStatus.error(message + " Port out of range [0-65535]."); } } catch (NumberFormatException e) { return ValidationStatus.error(message + " A number between [0-65535] is expected."); } return ValidationStatus.ok(); } }
7,122
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/page/validator/ContextPathValidator.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.codedeploy.deploy.wizard.page.validator; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; public class ContextPathValidator implements IValidator { public String message; public ContextPathValidator(String message) { this.message = message; } @Override public IStatus validate(Object value) { String s = (String)value; if (s == null || s.length() == 0) { return ValidationStatus.error(message); } if (s.contains("/") || s.contains("\\")) { return ValidationStatus.error(message + " Path must not contain slash."); } else if (s.contains(" ")) { return ValidationStatus.error(message + " Path must not contain space."); } return ValidationStatus.ok(); } }
7,123
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/deploy/wizard/model/DeployProjectToCodeDeployWizardDataModel.java
package com.amazonaws.eclipse.codedeploy.deploy.wizard.model; import java.util.Map; import org.eclipse.core.resources.IProject; import com.amazonaws.eclipse.codedeploy.appspec.model.AppspecTemplateMetadataModel; import com.amazonaws.eclipse.core.regions.Region; public class DeployProjectToCodeDeployWizardDataModel { public static final String REGION_PROPERTY = "region"; public static final String APPLICATION_NAME_PROPERTY = "applicationName"; public static final String DEPLOYMENT_GROUP_NAME_PROPERTY = "deploymentGroupName"; public static final String DEPLOYMENT_CONFIG_NAME_PROPERTY = "deploymentConfigName"; public static final String IGNORE_APPLICATION_STOP_FAILURES_PROPERTY = "ignoreApplicationStopFailures"; public static final String BUCKET_NAME_PROPERTY = "bucketName"; private final IProject project; /* Page 1 */ private Region region; private String applicationName; private String deploymentGroupName; /* Page 2 */ private String deploymentConfigName; private boolean ignoreApplicationStopFailures; private String bucketName; /* Page 3 */ private AppspecTemplateMetadataModel templateModel; private Map<String, String> templateParameterValues; /** * @param project * The Eclipse local project that is to be deployed. */ public DeployProjectToCodeDeployWizardDataModel(IProject project) { this.project = project; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getDeploymentGroupName() { return deploymentGroupName; } public void setDeploymentGroupName(String deploymentGroupName) { this.deploymentGroupName = deploymentGroupName; } public String getDeploymentConfigName() { return deploymentConfigName; } public void setDeploymentConfigName(String deploymentConfigName) { this.deploymentConfigName = deploymentConfigName; } public boolean isIgnoreApplicationStopFailures() { return ignoreApplicationStopFailures; } public void setIgnoreApplicationStopFailures( boolean ignoreApplicationStopFailures) { this.ignoreApplicationStopFailures = ignoreApplicationStopFailures; } public String getBucketName() { return bucketName; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public IProject getProject() { return project; } public AppspecTemplateMetadataModel getTemplateModel() { return templateModel; } public void setTemplateModel(AppspecTemplateMetadataModel templateModel) { this.templateModel = templateModel; } public Map<String, String> getTemplateParameterValues() { return templateParameterValues; } public void setTemplateParameterValues( Map<String, String> templateParameterValues) { this.templateParameterValues = templateParameterValues; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{") .append("Eclipse.Project=" + project.getName()) .append(", Region=" + region) .append(", Bucket=" + bucketName) .append(", Application=" + applicationName) .append(", DeploymentGroup=" + deploymentGroupName) .append(", DeploymentConfig=" + deploymentConfigName) .append(", IgnoreApplicationStopFailures=" + ignoreApplicationStopFailures) .append(", AppspecTemplateName=" + templateModel.getTemplateName()) .append(", AppspecTemplateParams=" + templateParameterValues) .append("}") ; return sb.toString(); } }
7,124
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/DeploymentGroupNode.java
package com.amazonaws.eclipse.codedeploy.explorer; import com.amazonaws.services.codedeploy.model.DeploymentGroupInfo; import com.amazonaws.services.codedeploy.model.DeploymentInfo; public class DeploymentGroupNode { private final DeploymentGroupInfo deploymentGroup; private final DeploymentInfo mostRecentDeployment; public DeploymentGroupNode(DeploymentGroupInfo deploymentGroup, DeploymentInfo mostRecentDeployment) { this.deploymentGroup = deploymentGroup; this.mostRecentDeployment = mostRecentDeployment; } public DeploymentGroupInfo getDeploymentGroup() { return deploymentGroup; } public DeploymentInfo getMostRecentDeployment() { return mostRecentDeployment; } }
7,125
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/DeploymentGroupNodeDecorator.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codedeploy.explorer; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ILightweightLabelDecorator; import com.amazonaws.services.codedeploy.model.DeploymentInfo; public class DeploymentGroupNodeDecorator implements ILightweightLabelDecorator { @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 void decorate(Object element, IDecoration decoration) { if (element instanceof DeploymentGroupNode) { DeploymentGroupNode node = (DeploymentGroupNode)element; DeploymentInfo mostRecentDeployment = node.getMostRecentDeployment(); if ( mostRecentDeployment != null ) { decoration.addSuffix(" (" + mostRecentDeployment.getStatus() + ")"); } } } }
7,126
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/CodeDeployActionProvider.java
package com.amazonaws.eclipse.codedeploy.explorer; import org.eclipse.jface.action.IMenuManager; import org.eclipse.ui.navigator.CommonActionProvider; public class CodeDeployActionProvider extends CommonActionProvider { @Override public void fillContextMenu(IMenuManager menu) { } }
7,127
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/CodeDeployLabelProvider.java
package com.amazonaws.eclipse.codedeploy.explorer; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.explorer.image.CodeDeployExplorerImages; import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider; import com.amazonaws.services.codedeploy.model.ApplicationInfo; public class CodeDeployLabelProvider extends ExplorerNodeLabelProvider { @Override public Image getDefaultImage(Object element) { ImageRegistry imageRegistry = CodeDeployPlugin.getDefault().getImageRegistry(); if ( element instanceof CodeDeployRootElement ) { return imageRegistry.get(CodeDeployExplorerImages.IMG_SERVICE); } if ( element instanceof ApplicationInfo ) { return imageRegistry.get(CodeDeployExplorerImages.IMG_APPLICATION); } if ( element instanceof DeploymentGroupNode ) { return imageRegistry.get(CodeDeployExplorerImages.IMG_DEPLOYMENT_GROUP); } return null; } @Override public String getText(Object element) { if ( element instanceof CodeDeployRootElement ) { return "AWS CodeDeploy"; } if ( element instanceof ApplicationInfo ) { ApplicationInfo app = (ApplicationInfo)element; return app.getApplicationName(); } if ( element instanceof DeploymentGroupNode ) { DeploymentGroupNode deployGroupNode = (DeploymentGroupNode)element; return deployGroupNode.getDeploymentGroup().getDeploymentGroupName(); } return getExplorerNodeText(element); } }
7,128
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/CodeDeployRootElement.java
package com.amazonaws.eclipse.codedeploy.explorer; /** * Root element for CodeDeploy resources in the resource navigator. */ public class CodeDeployRootElement { public static final CodeDeployRootElement ROOT_ELEMENT = new CodeDeployRootElement(); private CodeDeployRootElement() {} }
7,129
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/CodeDeployContentProvider.java
package com.amazonaws.eclipse.codedeploy.explorer; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import com.amazonaws.eclipse.codedeploy.ServiceAPIUtils; import com.amazonaws.eclipse.codedeploy.explorer.action.OpenDeploymentGroupEditorAction; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.explorer.AWSResourcesRootElement; import com.amazonaws.eclipse.explorer.AbstractContentProvider; import com.amazonaws.eclipse.explorer.Loading; import com.amazonaws.services.codedeploy.AmazonCodeDeploy; import com.amazonaws.services.codedeploy.model.ApplicationInfo; import com.amazonaws.services.codedeploy.model.DeploymentGroupInfo; import com.amazonaws.services.codedeploy.model.DeploymentInfo; public class CodeDeployContentProvider extends AbstractContentProvider { private static CodeDeployContentProvider instance; public CodeDeployContentProvider() { instance = this; } /* * Abstract methods of AbstractContentProvider */ @Override public boolean hasChildren(Object element) { return (element instanceof AWSResourcesRootElement || element instanceof CodeDeployRootElement || element instanceof ApplicationInfo); } @Override public Object[] loadChildren(Object parentElement) { if (parentElement instanceof AWSResourcesRootElement) { return new Object[] { CodeDeployRootElement.ROOT_ELEMENT }; } if (parentElement instanceof CodeDeployRootElement) { new DataLoaderThread(parentElement) { @Override public Object[] loadData() { AmazonCodeDeploy client = AwsToolkitCore.getClientFactory() .getCodeDeployClient(); return ServiceAPIUtils.getAllApplicationInfos(client).toArray(); } }.start(); } if (parentElement instanceof ApplicationInfo) { final String appName = ((ApplicationInfo) parentElement).getApplicationName(); new DataLoaderThread(parentElement) { @Override public Object[] loadData() { AmazonCodeDeploy client = AwsToolkitCore.getClientFactory() .getCodeDeployClient(); List<DeploymentGroupInfo> groups = ServiceAPIUtils .getAllDeploymentGroupInfos(client, appName); // Wrap the DeploymentGroupInfo objects into DeploymentGroupNodes List<DeploymentGroupNode> nodes = new LinkedList<>(); for (DeploymentGroupInfo group : groups) { DeploymentInfo mostRecentDeployment = ServiceAPIUtils .getMostRecentDeployment(client, appName, group.getDeploymentGroupName()); nodes.add(new DeploymentGroupNode(group, mostRecentDeployment)); } return nodes.toArray(); } }.start(); } return Loading.LOADING; } @Override public String getServiceAbbreviation() { return ServiceAbbreviations.CODE_DEPLOY; } @Override public void dispose() { viewer.removeOpenListener(listener); super.dispose(); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { super.inputChanged(viewer, oldInput, newInput); this.viewer.addOpenListener(listener); } public static CodeDeployContentProvider getInstance() { return instance; } private final IOpenListener listener = new IOpenListener() { @Override public void open(OpenEvent event) { StructuredSelection selection = (StructuredSelection)event.getSelection(); Iterator<?> i = selection.iterator(); while ( i.hasNext() ) { Object obj = i.next(); if ( obj instanceof DeploymentGroupNode ) { DeploymentGroupInfo group = ((DeploymentGroupNode) obj) .getDeploymentGroup(); OpenDeploymentGroupEditorAction action = new OpenDeploymentGroupEditorAction( group.getApplicationName(), group.getDeploymentGroupName(), RegionUtils.getCurrentRegion()); action.run(); } } } }; }
7,130
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/image/CodeDeployExplorerImages.java
package com.amazonaws.eclipse.codedeploy.explorer.image; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; public class CodeDeployExplorerImages { public static final String IMG_AWS_BOX = "aws-box"; public static final String IMG_SERVICE = "codedeploy-service"; public static final String IMG_APPLICATION = "application"; public static final String IMG_DEPLOYMENT_GROUP = "deploymentgroup"; public static final String IMG_CHECK_ICON = "check-icon"; public static ImageRegistry createImageRegistry() { ImageRegistry imageRegistry = new ImageRegistry(Display.getCurrent()); imageRegistry.put(IMG_AWS_BOX, ImageDescriptor.createFromFile(CodeDeployPlugin.class, "/icons/aws-box.gif")); imageRegistry.put(IMG_SERVICE, ImageDescriptor.createFromFile(CodeDeployPlugin.class, "/icons/codedeploy-service.png")); imageRegistry.put(IMG_APPLICATION, ImageDescriptor.createFromFile(CodeDeployPlugin.class, "/icons/application.png")); imageRegistry.put(IMG_DEPLOYMENT_GROUP, ImageDescriptor.createFromFile(CodeDeployPlugin.class, "/icons/deployment-group.png")); imageRegistry.put(IMG_CHECK_ICON, ImageDescriptor.createFromFile(CodeDeployPlugin.class, "/icons/12px-check-icon.png")); return imageRegistry; } }
7,131
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/action/OpenDeploymentGroupEditorAction.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codedeploy.explorer.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 com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.eclipse.codedeploy.explorer.editor.DeploymentGroupEditor; import com.amazonaws.eclipse.codedeploy.explorer.editor.DeploymentGroupEditorInput; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; public class OpenDeploymentGroupEditorAction extends AwsAction { private final String applicationName; private final String deploymentGroupName; private final Region region; public OpenDeploymentGroupEditorAction(String applicationName, String deploymentGroupName, Region region) { super(AwsToolkitMetricType.EXPLORER_CODEDEPLOY_OPEN_DEPLOYMENT_GROUP); this.applicationName = applicationName; this.deploymentGroupName = deploymentGroupName; this.region = region; this.setText("Open in Deployment Group Editor"); } @Override public void doRun() { String endpoint = region.getServiceEndpoint(ServiceAbbreviations.CODE_DEPLOY); String accountId = AwsToolkitCore.getDefault().getCurrentAccountId(); final IEditorInput input = new DeploymentGroupEditorInput( applicationName, deploymentGroupName, endpoint, accountId); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { IWorkbenchWindow activeWindow = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); activeWindow.getActivePage().openEditor(input, DeploymentGroupEditor.ID); actionSucceeded(); } catch (PartInitException e) { CodeDeployPlugin.getDefault().reportException( "Unable to open the Deployment Group editor", e); actionFailed(); } finally { actionFinished(); } } }); } }
7,132
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor/DeploymentGroupEditorInput.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codedeploy.explorer.editor; import org.eclipse.jface.resource.ImageDescriptor; import com.amazonaws.eclipse.codedeploy.explorer.image.CodeDeployExplorerImages; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput; import com.amazonaws.services.codedeploy.AmazonCodeDeploy; public final class DeploymentGroupEditorInput extends AbstractAwsResourceEditorInput { private final String applicationName; private final String deploymentGroupName; public DeploymentGroupEditorInput(String applicationName, String deploymentGroupName, String endpoint, String accountId) { super(endpoint, accountId); this.applicationName = applicationName; this.deploymentGroupName = deploymentGroupName; } @Override public String getToolTipText() { return "Amazon CodeDeploy deployment group - " + getName(); } @Override public String getName() { return String.format("%s [%s]", applicationName, deploymentGroupName); } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry() .getDescriptor(CodeDeployExplorerImages.IMG_DEPLOYMENT_GROUP); } public String getApplicationName() { return applicationName; } public String getDeploymentGroupName() { return deploymentGroupName; } public AmazonCodeDeploy getCodeDeployClient() { return AwsToolkitCore.getClientFactory().getCodeDeployClientByEndpoint( getRegionEndpoint()); } @Override public boolean equals(Object obj) { if ( !(obj instanceof DeploymentGroupEditorInput) ) return false; DeploymentGroupEditorInput otherEditor = (DeploymentGroupEditorInput) obj; return otherEditor.getApplicationName().equals(this.getApplicationName()) && otherEditor.getDeploymentGroupName().equals(this.getDeploymentGroupName()); } }
7,133
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor/DeploymentGroupEditor.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codedeploy.explorer.editor; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.resource.JFaceResources; 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.Display; 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.codedeploy.explorer.editor.table.DeploymentsTableView; import com.amazonaws.eclipse.codedeploy.explorer.image.CodeDeployExplorerImages; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.services.codedeploy.AmazonCodeDeploy; import com.amazonaws.services.codedeploy.model.AutoScalingGroup; import com.amazonaws.services.codedeploy.model.DeploymentGroupInfo; import com.amazonaws.services.codedeploy.model.EC2TagFilter; import com.amazonaws.services.codedeploy.model.GetDeploymentGroupRequest; public class DeploymentGroupEditor extends EditorPart { public final static String ID = "com.amazonaws.eclipse.codedeploy.explorer.editor.deploymentGroupEditor"; private DeploymentGroupEditorInput deploymentGroupEditorInput; private DeploymentsTableView deploymentsTable; public DeploymentsTableView getDeploymentsTableView() { return deploymentsTable; } @Override public void doSave(IProgressMonitor monitor) {} @Override public void doSaveAs() {} @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); deploymentGroupEditorInput = (DeploymentGroupEditorInput) input; setPartName(input.getName()); } @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 | SWT.H_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(deploymentGroupEditorInput.getName()); toolkit.decorateFormHeading(form.getForm()); form.setImage(AwsToolkitCore.getDefault().getImageRegistry() .get(CodeDeployExplorerImages.IMG_DEPLOYMENT_GROUP)); form.getBody().setLayout(new GridLayout(1, false)); createDeploymentGroupSummary(form, toolkit); createDeploymentHistoryTable(form, toolkit); form.getToolBarManager().add(new RefreshAction()); form.getToolBarManager().update(true); } private class RefreshAction extends AwsAction { public RefreshAction() { super(AwsToolkitMetricType.EXPLORER_CODEDEPLOY_REFRESH_DEPLOYMENT_GROUP_EDITOR); this.setText("Refresh"); this.setToolTipText("Refresh deployment history"); this.setImageDescriptor(AwsToolkitCore.getDefault() .getImageRegistry() .getDescriptor(AwsToolkitCore.IMAGE_REFRESH)); } @Override protected void doRun() { deploymentsTable.refreshAsync(); actionFinished(); } } /** * Creates the table of deployment histories */ private void createDeploymentHistoryTable(final ScrolledForm form, final FormToolkit toolkit) { deploymentsTable = new DeploymentsTableView( deploymentGroupEditorInput, form.getBody(), toolkit, SWT.None); deploymentsTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); } /** * Creates a summary of a the deployment group */ private void createDeploymentGroupSummary(final ScrolledForm form, final FormToolkit toolkit) { final Composite parent = toolkit.createComposite(form.getBody(), SWT.None); parent.setLayout(new GridLayout(2, false)); toolkit.createLabel(parent, "Deployment Group info loading"); toolkit.createLabel(parent, ""); new Thread() { @Override public void run() { AmazonCodeDeploy codeDeployClient = deploymentGroupEditorInput .getCodeDeployClient(); DeploymentGroupInfo deployGroupInfo = codeDeployClient.getDeploymentGroup( new GetDeploymentGroupRequest() .withApplicationName(deploymentGroupEditorInput.getApplicationName()) .withDeploymentGroupName(deploymentGroupEditorInput.getDeploymentGroupName()) ) .getDeploymentGroupInfo(); if ( deployGroupInfo == null ) return; updateComposite(form, toolkit, deployGroupInfo); } protected void updateComposite(final ScrolledForm form, final FormToolkit toolkit, final DeploymentGroupInfo deployGroup) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { for ( Control c : parent.getChildren() ) { c.dispose(); } toolkit.createLabel(parent, "Application Name: "); toolkit.createText(parent, deployGroup.getApplicationName(), SWT.READ_ONLY); toolkit.createLabel(parent, "Deployment Group Name: "); toolkit.createText(parent, deployGroup.getDeploymentGroupName(), SWT.READ_ONLY); toolkit.createLabel(parent, "Deployment Group ID: "); toolkit.createText(parent, deployGroup.getDeploymentGroupId(), SWT.READ_ONLY); toolkit.createLabel(parent, "Service Role ARN: "); toolkit.createText(parent, deployGroup.getServiceRoleArn(), SWT.READ_ONLY); toolkit.createLabel(parent, "Deployment Configuration: "); toolkit.createText(parent, deployGroup.getDeploymentConfigName(), SWT.READ_ONLY); if (deployGroup.getEc2TagFilters() != null && !deployGroup.getEc2TagFilters().isEmpty()) { toolkit.createLabel(parent, "Amazon EC2 Tags: "); StringBuilder tags = new StringBuilder(); boolean first = true; for (EC2TagFilter tag : deployGroup.getEc2TagFilters()) { if (first) { first = false; } else { tags.append(", "); } if ("KEY_AND_VALUE".equals(tag.getType())) { tags.append(tag.getKey() + ":" + tag.getValue()); } else if ("KEY_ONLY".equals(tag.getType())) { tags.append(tag.getKey() + "(KEY_ONLY)"); } else if ("VALUE_ONLY".equals(tag.getType())) { tags.append(tag.getValue() + "(VALUE_ONLY)"); } } toolkit.createText(parent, tags.toString(), SWT.READ_ONLY); } if (deployGroup.getAutoScalingGroups() != null && !deployGroup.getAutoScalingGroups().isEmpty()) { toolkit.createLabel(parent, "Associated Auto Scaling Groups: "); StringBuilder groups = new StringBuilder(); boolean first = true; for (AutoScalingGroup group : deployGroup.getAutoScalingGroups()) { if (first) { first = false; } else { groups.append(", "); } groups.append(group.getName() + ":" + group.getHook()); } toolkit.createText(parent, groups.toString(), SWT.READ_ONLY); } form.reflow(true); } }); } }.start(); } @Override public void setFocus() { } }
7,134
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor/table/DeploymentsTableViewContentProvider.java
package com.amazonaws.eclipse.codedeploy.explorer.editor.table; import org.eclipse.jface.viewers.ILazyTreePathContentProvider; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; class DeploymentsTableViewContentProvider implements ILazyTreePathContentProvider { private TreePathContentProvider input; private TreeViewer viewer; public DeploymentsTableViewContentProvider(TreeViewer viewer, TreePathContentProvider input) { this.viewer = viewer; this.input = input; } @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput == null) { return; } if ( !(newInput instanceof TreePathContentProvider) ) { throw new IllegalStateException( "The new input passed to the DeploymentsTableViewContentProvider " + "is not a TreePathContentProvider!"); } this.viewer = (TreeViewer) viewer; this.input = (TreePathContentProvider) newInput; } @Override public void updateElement(TreePath parentPath, int index) { Object[] children = input.getChildren(parentPath); if (index >= children.length) { return; } viewer.replace(parentPath, index, children[index]); updateHasChildren(parentPath.createChildPath(children[index])); } @Override public void updateChildCount(TreePath treePath, int currentChildCount) { Object[] children = input.getChildren(treePath); viewer.setChildCount(treePath, children.length); } @Override public void updateHasChildren(TreePath path) { Object[] children = input.getChildren(path); viewer.setHasChildren(path, children.length != 0); } @Override public TreePath[] getParents(Object element) { return null; } }
7,135
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor/table/DeploymentsTableViewLabelProvider.java
package com.amazonaws.eclipse.codedeploy.explorer.editor.table; import static com.amazonaws.eclipse.codedeploy.explorer.editor.table.DeploymentsTableView.DEPLOYMENT_ID_COL; import static com.amazonaws.eclipse.codedeploy.explorer.editor.table.DeploymentsTableView.END_TIME_COL; import static com.amazonaws.eclipse.codedeploy.explorer.editor.table.DeploymentsTableView.INSTANCE_ID_COL; import static com.amazonaws.eclipse.codedeploy.explorer.editor.table.DeploymentsTableView.LIFECYCLE_EVENT_COL; import static com.amazonaws.eclipse.codedeploy.explorer.editor.table.DeploymentsTableView.LOGS_COL; import static com.amazonaws.eclipse.codedeploy.explorer.editor.table.DeploymentsTableView.REVISION_LOCATION_COL; import static com.amazonaws.eclipse.codedeploy.explorer.editor.table.DeploymentsTableView.START_TIME_COL; import static com.amazonaws.eclipse.codedeploy.explorer.editor.table.DeploymentsTableView.STATUS_COL; import java.util.Date; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.codedeploy.CodeDeployPlugin; import com.amazonaws.services.codedeploy.model.DeploymentInfo; import com.amazonaws.services.codedeploy.model.DeploymentOverview; import com.amazonaws.services.codedeploy.model.ErrorInformation; import com.amazonaws.services.codedeploy.model.InstanceSummary; import com.amazonaws.services.codedeploy.model.LifecycleEvent; import com.amazonaws.services.codedeploy.model.RevisionLocation; class DeploymentsTableViewLabelProvider extends StyledCellLabelProvider { @Override public void update(ViewerCell cell) { String text = getColumnText(cell.getElement(), cell.getColumnIndex()); cell.setText(text); if (cell.getColumnIndex() == STATUS_COL) { if ("Succeeded".equals(text)) { cell.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_DARK_GREEN)); } else if ("Failed".equals(text)) { cell.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_RED)); } else if (cell.getElement() != LoadingContentProvider.LOADING ){ cell.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); } } super.update(cell); // calls 'repaint' to trigger the paint listener } private String getColumnText(Object element, int columnIndex) { if ( element == LoadingContentProvider.LOADING ) { return "Loading..."; } try { if (element instanceof DeploymentInfo) { DeploymentInfo deployment = (DeploymentInfo) element; switch (columnIndex) { case DEPLOYMENT_ID_COL: return deployment.getDeploymentId(); case INSTANCE_ID_COL: return getInstancesOverviewString(deployment); case START_TIME_COL: return getDateString(deployment.getCreateTime()); case END_TIME_COL: return getDateString(deployment.getCompleteTime()); case STATUS_COL: return deployment.getStatus(); case REVISION_LOCATION_COL: RevisionLocation revision = deployment.getRevision(); if ("S3".equals(revision.getRevisionType())) { return String.format("s3://%s/%s", revision.getS3Location().getBucket(), revision.getS3Location().getKey()); } else if ("GitHub".equals(revision.getRevisionType())) { return String.format("github://%s/%s", revision.getGitHubLocation().getRepository(), revision.getGitHubLocation().getCommitId()); } return ""; case LOGS_COL: ErrorInformation error = deployment.getErrorInformation(); return error == null ? "" : String.format("[%s] %s", error.getCode(), error.getMessage()); } } if (element instanceof InstanceSummary) { InstanceSummary instance = (InstanceSummary) element; switch (columnIndex) { case INSTANCE_ID_COL: return extractInstanceId(instance.getInstanceId()); case START_TIME_COL: if (instance.getLifecycleEvents() != null && !instance.getLifecycleEvents().isEmpty()) { return getDateString(instance.getLifecycleEvents().get(0).getStartTime()); } else { return ""; } case END_TIME_COL: if (instance.getLifecycleEvents() != null && !instance.getLifecycleEvents().isEmpty()) { return getDateString(instance.getLifecycleEvents() .get(instance.getLifecycleEvents().size() - 1) .getEndTime()); } else { return ""; } case STATUS_COL: return instance.getStatus(); } } if (element instanceof LifecycleEvent) { LifecycleEvent event = (LifecycleEvent) element; switch (columnIndex) { case LIFECYCLE_EVENT_COL: return event.getLifecycleEventName(); case START_TIME_COL: return getDateString(event.getStartTime()); case END_TIME_COL: return getDateString(event.getEndTime()); case STATUS_COL: return event.getStatus(); case LOGS_COL: return event.getDiagnostics() == null ? "" : event.getDiagnostics().getErrorCode(); } } } catch (Exception e) { CodeDeployPlugin.getDefault().reportException( "Unable to display " + element.getClass().getName() + " in the Deployment Group Editor.", e); } return ""; } private static String getDateString(Date date) { return date == null ? "" : date.toGMTString(); } private static String extractInstanceId(String instanceArn) { int index = instanceArn.lastIndexOf("/"); return instanceArn.substring(index + 1); } private static String getInstancesOverviewString(DeploymentInfo deployment) { DeploymentOverview overview = deployment.getDeploymentOverview(); if (overview == null) { return ""; } long total = overview.getFailed() + overview.getInProgress() + overview.getPending() + overview.getSkipped() + overview.getSucceeded(); return String.format("(%d of %d completed)", overview.getSucceeded(), total); } }
7,136
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor/table/DeploymentsTableViewTreePathContentCache.java
package com.amazonaws.eclipse.codedeploy.explorer.editor.table; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.eclipse.jface.viewers.TreePath; import com.amazonaws.eclipse.codedeploy.ServiceAPIUtils; import com.amazonaws.eclipse.codedeploy.explorer.editor.DeploymentGroupEditorInput; import com.amazonaws.services.codedeploy.model.DeploymentInfo; import com.amazonaws.services.codedeploy.model.InstanceSummary; import com.amazonaws.services.codedeploy.model.LifecycleEvent; /** * @ThreadSafe */ class DeploymentsTableViewTreePathContentCache implements TreePathContentProvider { private final Map<TreePath, Object[]> cache; private final DeploymentGroupEditorInput editorInput; public DeploymentsTableViewTreePathContentCache(DeploymentGroupEditorInput editorInput) { this.editorInput = editorInput; cache = new ConcurrentHashMap<>(); } @Override public Object[] getChildren(TreePath parent) { if ( !cache.containsKey(parent) ) { cache.put(parent, loadChildren(parent)); } return cache.get(parent); } @Override public void refresh() { cache.clear(); } private Object[] loadChildren(TreePath parent) { if (parent.getSegmentCount() == 0) { // root List<DeploymentInfo> deployments = ServiceAPIUtils.getAllDeployments( editorInput.getCodeDeployClient(), editorInput.getApplicationName(), editorInput.getDeploymentGroupName()); // Sort by creation data Collections.sort(deployments, new Comparator<DeploymentInfo>() { @Override public int compare(DeploymentInfo a, DeploymentInfo b) { int a_to_b = a.getCreateTime().compareTo(b.getCreateTime()); // In descending order return - a_to_b; } }); return deployments.toArray(new DeploymentInfo[deployments.size()]); } else { Object lastSegment = parent.getLastSegment(); if (lastSegment instanceof DeploymentInfo) { DeploymentInfo deployment = (DeploymentInfo) lastSegment; List<InstanceSummary> instances = ServiceAPIUtils.getAllDeploymentInstances( editorInput.getCodeDeployClient(), deployment.getDeploymentId()); return instances.toArray(new InstanceSummary[instances.size()]); } else if (lastSegment instanceof InstanceSummary) { InstanceSummary deploymentInstance = (InstanceSummary) lastSegment; List<LifecycleEvent> events = deploymentInstance.getLifecycleEvents(); if (events == null) { events = new LinkedList<>(); } return events.toArray(new LifecycleEvent[events.size()]); } } return new Object[0]; } }
7,137
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor/table/DeploymentsTableView.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codedeploy.explorer.editor.table; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ColumnPixelData; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; 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.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.widgets.FormToolkit; import com.amazonaws.eclipse.codedeploy.explorer.editor.DeploymentGroupEditorInput; /** * S3 object listing with virtual directory support. */ public class DeploymentsTableView extends Composite { static final int DEPLOYMENT_ID_COL = 0; static final int INSTANCE_ID_COL = 1; static final int LIFECYCLE_EVENT_COL = 2; static final int STATUS_COL = 3; static final int START_TIME_COL = 4; static final int END_TIME_COL = 5; static final int REVISION_LOCATION_COL = 6; static final int LOGS_COL = 7; private final TreeViewer viewer; private final DeploymentsTableViewTreePathContentCache contentCache; private final LoadingContentProvider loadingContentProvider; private Label tableTitleLabel; public DeploymentsTableView(DeploymentGroupEditorInput editorInput, Composite composite, FormToolkit toolkit, int style) { super(composite, style); contentCache = new DeploymentsTableViewTreePathContentCache(editorInput); loadingContentProvider = new LoadingContentProvider(); viewer = createControls(toolkit); } private TreeViewer createControls(FormToolkit toolkit) { GridLayout gridLayout = new GridLayout(1, false); gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; setLayout(gridLayout); Composite sectionComp = toolkit.createComposite(this, SWT.None); sectionComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); sectionComp.setLayout(new GridLayout(1, false)); Composite headingComp = toolkit.createComposite(sectionComp, SWT.None); headingComp.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); headingComp.setLayout(new GridLayout()); tableTitleLabel = toolkit.createLabel(headingComp, "Deployments"); tableTitleLabel.setFont(JFaceResources.getHeaderFont()); tableTitleLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); Composite tableHolder = toolkit.createComposite(sectionComp, SWT.None); tableHolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); FillLayout layout = new FillLayout(); layout.marginHeight = 0; layout.marginWidth = 10; layout.type = SWT.VERTICAL; tableHolder.setLayout(layout); Composite tableComp = toolkit.createComposite(tableHolder, SWT.None); final TreeColumnLayout tableColumnLayout = new TreeColumnLayout(); tableComp.setLayout(tableColumnLayout); final TreeViewer viewer = new TreeViewer(tableComp, SWT.BORDER | SWT.VIRTUAL | SWT.MULTI | SWT.H_SCROLL); viewer.getTree().setLinesVisible(true); viewer.getTree().setHeaderVisible(true); viewer.setUseHashlookup(true); viewer.setLabelProvider(new DeploymentsTableViewLabelProvider()); viewer.setContentProvider(new DeploymentsTableViewContentProvider(this.viewer, this.contentCache)); Tree tree = viewer.getTree(); createColumns(tableColumnLayout, tree); viewer.setInput(loadingContentProvider); updateRefreshProgress(0, false); // Async load top-level data new Thread(new Runnable() { @Override public void run() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { // Preserve the current column widths int[] colWidth = new int[viewer.getTree().getColumns().length]; int i = 0; for ( TreeColumn col : viewer.getTree().getColumns() ) { colWidth[i++] = col.getWidth(); } i = 0; for ( TreeColumn col : viewer.getTree().getColumns() ) { tableColumnLayout.setColumnData(col, new ColumnPixelData(colWidth[i])); } } }); // Cache the children of all the top-level elements before // updating the tree view loadAllTopLevelElements(); Display.getDefault().syncExec(new Runnable() { @Override public void run() { viewer.setInput(contentCache); } }); } }).start(); return viewer; } private void createColumns(TreeColumnLayout tableColumnLayout, Tree tree) { TreeColumn column = new TreeColumn(tree, SWT.NONE); column.setText("Deployment ID"); ColumnWeightData cwd_column = new ColumnWeightData(10); cwd_column.minimumWidth = 1; tableColumnLayout.setColumnData(column, cwd_column); TreeColumn column_1 = new TreeColumn(tree, SWT.NONE); column_1.setText("EC2 Instance"); tableColumnLayout.setColumnData(column_1, new ColumnWeightData(10)); TreeColumn column_2 = new TreeColumn(tree, SWT.NONE); column_2.setText("Lifecycle Event"); tableColumnLayout.setColumnData(column_2, new ColumnWeightData(8)); TreeColumn column_3 = new TreeColumn(tree, SWT.NONE); column_3.setText("Status"); tableColumnLayout.setColumnData(column_3, new ColumnWeightData(6)); TreeColumn column_4 = new TreeColumn(tree, SWT.NONE); column_4.setText("Start Time"); tableColumnLayout.setColumnData(column_4, new ColumnWeightData(12)); TreeColumn column_5 = new TreeColumn(tree, SWT.NONE); column_5.setText("End Time"); tableColumnLayout.setColumnData(column_5, new ColumnWeightData(12)); TreeColumn column_6 = new TreeColumn(tree, SWT.NONE); column_6.setText("Revision"); tableColumnLayout.setColumnData(column_6, new ColumnWeightData(20)); TreeColumn column_7 = new TreeColumn(tree, SWT.NONE); column_7.setText("Logs"); tableColumnLayout.setColumnData(column_7, new ColumnWeightData(15)); } private volatile boolean isRefreshing = false; public void refreshAsync() { if (isRefreshing) { return; } new Thread(new Runnable() { @Override public void run() { isRefreshing = true; updateRefreshProgress(0, true); // Cache the children of all the top-level elements before // updating the tree view contentCache.refresh(); loadAllTopLevelElements(); Display.getDefault().syncExec(new Runnable() { @Override public void run() { viewer.setInput(contentCache); } }); isRefreshing = false; } }).start(); } private void loadAllTopLevelElements() { Object[] topLevelElements = contentCache .getChildren(new TreePath(new Object[0])); int progressPerElement = 100 / (topLevelElements.length + 1); int loadedElements = 1; updateRefreshProgress(loadedElements++ * progressPerElement, true); for (Object topLevelElement : topLevelElements) { contentCache.getChildren(new TreePath( new Object[] { topLevelElement })); updateRefreshProgress(loadedElements++ * progressPerElement, true); } Display.getDefault().syncExec(new Runnable() { @Override public void run() { tableTitleLabel.setText("Deployments"); tableTitleLabel.pack(); } }); } private void updateRefreshProgress(final int progress, boolean inDisplayThread) { if (inDisplayThread) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { updateRefreshProgress(progress, false); } }); } else { tableTitleLabel.setText(String.format( "Deployments (loading... %d%%)", Math.min(100, progress))); tableTitleLabel.pack(); } } }
7,138
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor/table/TreePathContentProvider.java
package com.amazonaws.eclipse.codedeploy.explorer.editor.table; import org.eclipse.jface.viewers.TreePath; interface TreePathContentProvider { Object[] getChildren(TreePath parent); void refresh(); }
7,139
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codedeploy/src/com/amazonaws/eclipse/codedeploy/explorer/editor/table/LoadingContentProvider.java
package com.amazonaws.eclipse.codedeploy.explorer.editor.table; import org.eclipse.jface.viewers.TreePath; class LoadingContentProvider implements TreePathContentProvider { static final Object LOADING = new Object(); @Override public Object[] getChildren(TreePath parent) { if (parent.getSegmentCount() == 0) { return new Object[] {LOADING}; } else { return new Object[0]; } } @Override public void refresh() { } }
7,140
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/AbstractAddNewAttributeDialog.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.dynamodb; 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 abstract class AbstractAddNewAttributeDialog extends MessageDialog { String newAttributeName = ""; public String getNewAttributeName() { return newAttributeName.trim(); } protected AbstractAddNewAttributeDialog() { super(Display.getCurrent().getActiveShell(), "Enter New Attribute Name", null, "Enter a new attribute name", MessageDialog.NONE, new String[] { "OK", "Cancel" }, 0); } @Override protected Control createCustomArea(Composite parent) { final Text text = new Text(parent, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(text); text.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { newAttributeName = text.getText(); validate(); } }); return parent; } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); validate(); } abstract public void validate(); }
7,141
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/DynamoDBPlugin.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.dynamodb; import java.util.Arrays; import java.util.Iterator; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.osgi.framework.BundleContext; import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.dynamodb.preferences.TestToolPreferencePage; import com.amazonaws.eclipse.dynamodb.testtool.TestToolManager; /** * The activator class controls the plug-in life cycle */ public class DynamoDBPlugin extends AbstractAwsPlugin { public static final String IMAGE_ONE = "1"; public static final String IMAGE_A = "a"; public static final String IMAGE_TABLE = "table"; public static final String IMAGE_NEXT_RESULTS = "next_results"; public static final String IMAGE_ADD = "add"; public static final String IMAGE_REMOVE = "remove"; public static final String IMAGE_DYNAMODB_SERVICE = "dynamodb-service"; // The plug-in ID public static final String PLUGIN_ID = "com.amazonaws.eclipse.dynamodb"; //$NON-NLS-1$ // The shared instance private static DynamoDBPlugin plugin; private IPropertyChangeListener listener; /** * The constructor */ public DynamoDBPlugin() { } /* * (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; setDefaultDynamoDBLocalPort(); listener = new DefaultTestToolPortListener(); getPreferenceStore().addPropertyChangeListener(listener); } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; if (listener != null) { getPreferenceStore().removePropertyChangeListener(listener); listener = null; } super.stop(context); } /** * Register a local DynamoDB service on the configured default port for * DynamoDB Local. This will cause the DynamoDB node to show up on the * Local region of the explorer, so you can connect to it if you've * started DynamoDB Local from outside of Eclipse. */ public void setDefaultDynamoDBLocalPort() { int defaultPort = getPreferenceStore() .getInt(TestToolPreferencePage.DEFAULT_PORT_PREFERENCE_NAME); RegionUtils.addLocalService(ServiceAbbreviations.DYNAMODB, "dynamodb", defaultPort); } /** * Returns the shared instance * * @return the shared instance */ public static DynamoDBPlugin getDefault() { return plugin; } /* (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#createImageRegistry() */ @Override protected ImageRegistry createImageRegistry() { String[] images = new String[] { IMAGE_ONE, "/icons/1.png", IMAGE_A, "/icons/a.png", IMAGE_TABLE, "/icons/table.png", IMAGE_NEXT_RESULTS, "/icons/next_results.png", IMAGE_ADD, "/icons/add.png", IMAGE_REMOVE, "/icons/remove.gif", IMAGE_DYNAMODB_SERVICE, "/icons/dynamodb-service.png", }; ImageRegistry imageRegistry = super.createImageRegistry(); Iterator<String> i = Arrays.asList(images).iterator(); while (i.hasNext()) { String id = i.next(); String imagePath = i.next(); imageRegistry.put(id, ImageDescriptor.createFromFile(getClass(), imagePath)); } return imageRegistry; } /** * Property change listener that updates the endpoint registered with the * "Local" psuedo-region. */ private static class DefaultTestToolPortListener implements IPropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent event) { if ((event.getProperty() == TestToolPreferencePage.DEFAULT_PORT_PREFERENCE_NAME) && !TestToolManager.INSTANCE.isRunning()) { RegionUtils.addLocalService(ServiceAbbreviations.DYNAMODB, "dynamodb", (Integer) event.getNewValue()); } } } }
7,142
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/preferences/PreferenceInitializer.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.dynamodb.preferences; import java.io.File; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; public class PreferenceInitializer extends AbstractPreferenceInitializer { public static final String DEFAULT_DOWNLOAD_DIRECTORY; static { File userHome = new File(System.getProperty("user.home")); DEFAULT_DOWNLOAD_DIRECTORY = new File(userHome, "dynamodb-local").getAbsolutePath(); } public static final int DEFAULT_PORT = 8000; @Override public void initializeDefaultPreferences() { IPreferenceStore store = DynamoDBPlugin.getDefault().getPreferenceStore(); store.setDefault( TestToolPreferencePage.DOWNLOAD_DIRECTORY_PREFERENCE_NAME, DEFAULT_DOWNLOAD_DIRECTORY ); store.setDefault( TestToolPreferencePage.DEFAULT_PORT_PREFERENCE_NAME, DEFAULT_PORT ); } }
7,143
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/preferences/TestToolPreferencePage.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.dynamodb.preferences; import org.eclipse.jface.preference.DirectoryFieldEditor; import org.eclipse.jface.preference.FieldEditor; import org.eclipse.jface.preference.IntegerFieldEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.dialogs.PreferencesUtil; import com.amazonaws.eclipse.core.ui.preferences.AwsToolkitPreferencePage; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.eclipse.dynamodb.testtool.TestToolManager; import com.amazonaws.eclipse.dynamodb.testtool.TestToolVersionTable; public class TestToolPreferencePage extends AwsToolkitPreferencePage implements IWorkbenchPreferencePage { public static final String DOWNLOAD_DIRECTORY_PREFERENCE_NAME = "com.amazonaws.eclipse.dynamodb.local.preferences.downloadDirectory"; public static final String DEFAULT_PORT_PREFERENCE_NAME = "com.amazonaws.eclipse.dynamodb.local.preferences.defaultPort"; private static final int MAX_FIELD_EDITOR_COLUMNS = 3; private DirectoryFieldEditor downloadDirectory; private IntegerFieldEditor defaultPort; public TestToolPreferencePage() { super("DynamoDB Local Test Tool"); } /** {@inheritDoc} */ @Override public void init(final IWorkbench workbench) { setPreferenceStore(DynamoDBPlugin.getDefault().getPreferenceStore()); } @Override protected Control createContents(final Composite parent) { final Composite composite = new Composite(parent, SWT.LEFT); composite.setLayout(new GridLayout()); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); if (TestToolManager.INSTANCE.isJava7Available()) { Composite group = new Composite(composite, SWT.LEFT); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); createDownloadDirectory(group); createDefaultPort(group); GridLayout layout = (GridLayout) group.getLayout(); layout.numColumns = MAX_FIELD_EDITOR_COLUMNS; TestToolVersionTable versionTable = new TestToolVersionTable(composite); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); data.heightHint = 400; versionTable.setLayoutData(data); } else { Label warning = new Label(composite, SWT.WRAP); warning.setText("The DynamoDB Local Test Tool requires a " + "JavaSE-1.8 compatible execution environment!"); GridData data = new GridData(SWT.LEFT, SWT.TOP, true, false); data.widthHint = 500; warning.setLayoutData(data); Link link = new Link(composite, SWT.NONE); link.setText("Click <A>here</A> to configure Installed JREs"); link.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { PreferencesUtil.createPreferenceDialogOn( composite.getShell(), "org.eclipse.jdt.debug.ui.preferences.VMPreferencePage", null, null ); } }); link.setToolTipText("Configure Installed JREs"); data = new GridData(SWT.LEFT, SWT.TOP, true, false); data.widthHint = 500; link.setLayoutData(data); } return composite; } @Override protected void performDefaults() { if (downloadDirectory != null) { downloadDirectory.loadDefault(); } if (defaultPort != null) { defaultPort.loadDefault(); } super.performDefaults(); } @Override public boolean performOk() { if (downloadDirectory != null) { downloadDirectory.store(); } if (defaultPort != null) { defaultPort.store(); } return super.performOk(); } @Override public void performApply() { if (downloadDirectory != null) { downloadDirectory.store(); } if (defaultPort != null) { defaultPort.store(); } super.performApply(); } private void createDownloadDirectory(final Composite composite) { downloadDirectory = new DirectoryFieldEditor( DOWNLOAD_DIRECTORY_PREFERENCE_NAME, "Install Directory:", composite ); customizeEditor(composite, downloadDirectory); } private void createDefaultPort(final Composite composite) { defaultPort = new IntegerFieldEditor( DEFAULT_PORT_PREFERENCE_NAME, "Default Port:", composite ); customizeEditor(composite, defaultPort); } private void customizeEditor(final Composite composite, final FieldEditor editor) { editor.setPage(this); editor.setPreferenceStore(getPreferenceStore()); editor.load(); editor.fillIntoGrid(composite, MAX_FIELD_EDITOR_COLUMNS); } }
7,144
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/testtool/StartTestToolPickVersionWizardPage.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.dynamodb.testtool; 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.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.layout.GridDataFactory; 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 com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.databinding.ChainValidator; /** * A wizard page that allows the user to pick an installed version of the * DynamoDBLocal test tool to be started, or to install a version of the test * tool if one is not yet installed. */ public class StartTestToolPickVersionWizardPage extends WizardPage { private final DataBindingContext context = new DataBindingContext(); private final IObservableValue versionSelection = new WritableValue(); private TestToolVersionTable versionTable; /** * Create the page. */ public StartTestToolPickVersionWizardPage() { super("Choose a Version"); super.setMessage("Choose a version of the DynamoDB Local Test Tool " + "to start"); super.setImageDescriptor( AwsToolkitCore.getDefault() .getImageRegistry() .getDescriptor("dynamodb-service") ); } /** * @return the currently selected version */ public TestToolVersion getSelectedVersion() { return (TestToolVersion) versionSelection.getValue(); } /** * Create the version table control. * * @param parent the parent composite to attach the control to */ @Override public void createControl(final Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); composite.setLayout(new GridLayout()); versionTable = new TestToolVersionTable(composite); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); data.heightHint = 400; versionTable.setLayoutData(data); // TODO: Worth adding some text here to explain to the user that they // must pick an installed version of the test tool, and that they may // install a version if needed? I'm hoping it's self-evident? bindInputs(); context.updateModels(); setControl(composite); } /** * Bind the UI to the internal model and set up a validator to ensure an * installed version of the tool is selected before this page is complete. */ private void bindInputs() { IObservableValue observable = versionTable.getObservableSelection(); context.bindValue(observable, versionSelection); context.addValidationStatusProvider( new ChainValidator<TestToolVersion>( observable, new TestToolVersionValidator() ) ); final AggregateValidationStatus aggregator = new AggregateValidationStatus(context, AggregateValidationStatus.MAX_SEVERITY); aggregator.addChangeListener(new IChangeListener() { @Override public void handleChange(final ChangeEvent event) { Object value = aggregator.getValue(); if (!(value instanceof IStatus)) { return; } IStatus status = (IStatus) value; setPageComplete(status.isOK()); } }); } /** * A validator that ensures an installed version of the test tool is * chosen. */ private static class TestToolVersionValidator implements IValidator { @Override public IStatus validate(final Object value) { if (!(value instanceof TestToolVersion)) { return ValidationStatus.error("No version selected"); } TestToolVersion version = (TestToolVersion) value; if (!version.isInstalled()) { return ValidationStatus.error("Version is not installed"); } return ValidationStatus.ok(); } } }
7,145
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/testtool/TestToolManager.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.dynamodb.testtool; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.launching.environments.IExecutionEnvironment; import org.eclipse.jdt.launching.environments.IExecutionEnvironmentsManager; import org.eclipse.jface.preference.IPreferenceStore; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; import com.amazonaws.AmazonServiceException; import com.amazonaws.eclipse.core.AWSClientFactory; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.eclipse.dynamodb.preferences.TestToolPreferencePage; import com.amazonaws.eclipse.dynamodb.testtool.TestToolVersion.InstallState; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.transfer.Download; import com.amazonaws.services.s3.transfer.TransferManager; /** * The singleton manager for DynamoDB Local Test Tool instances. */ public class TestToolManager { public static final TestToolManager INSTANCE = new TestToolManager(); private static final String TEST_TOOL_BUCKET = "aws-toolkits-dynamodb-local"; private static final String TEST_TOOL_MANIFEST = "manifest.xml"; private static final Pattern WHITESPACE = Pattern.compile("\\s+"); private final Set<String> installing = Collections.synchronizedSet(new HashSet<String>()); private TransferManager transferManager; private List<TestToolVersion> versions; private TestToolVersion currentlyRunningVersion; private TestToolProcess currentProcess; private TestToolManager() { } /** * Get a list of all versions of the DynamoDB Local Test Tool which can * be installed on the system. The first time this method is called, it * attempts to pull the list of versions from S3 (falling back to an * on-disk cache in case of failure). On subsequent calls it returns the * in-memory cache (updated to reflect the current state of what is and * is not installed). * * @return the list of all local test tool versions */ public synchronized List<TestToolVersion> getAllVersions() { if (versions == null) { versions = loadVersions(); } else { versions = refreshInstallStates(versions); } return versions; } /** * Determines whether a Java 7 compatible JRE exists on the system. * * @return true if a Java 7 compatible JRE is found, false otherwise */ public boolean isJava7Available() { return (getJava7VM() != null); } /** * Gets a Java 7 compatible VM, if one can be found. * * @return the VM install, or null if none was found */ private IVMInstall getJava7VM() { IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager(); IExecutionEnvironment environment = manager.getEnvironment("JavaSE-1.8"); if (environment == null) { // This version of Eclipse doesn't even know that Java 7 exists. return null; } IVMInstall defaultVM = environment.getDefaultVM(); if (defaultVM != null) { // If the user has set a default VM to use for Java 7, go with // that. return defaultVM; } IVMInstall[] installs = environment.getCompatibleVMs(); if (installs != null && installs.length > 0) { // Otherwise just pick the latest compatible VM. return installs[installs.length - 1]; } // No compatible VMs installed. return null; } /** * Set the install state of the given instance to INSTALLING, so that * we disable both the install and uninstall buttons in the UI. * * @param version The version to mark as INSTALLING. */ public synchronized void markInstalling(final TestToolVersion version) { if (!version.isInstalled()) { installing.add(version.getName()); } } /** * Install the given version of the test tool. * * @param version The version of the test tool to install. * @param monitor A progress monitor to keep updated. */ public void installVersion(final TestToolVersion version, final IProgressMonitor monitor) { if (version.isInstalled()) { return; } try { File tempFile = File.createTempFile("dynamodb_local_", ""); tempFile.delete(); if (!tempFile.mkdirs()) { throw new RuntimeException("Failed to create temporary " + "directory for download"); } File zipFile = new File(tempFile, "dynamodb_local.zip"); download(version.getDownloadKey(), zipFile, monitor); File unzipped = new File(tempFile, "unzipped"); if (!unzipped.mkdirs()) { throw new RuntimeException("Failed to create temporary " + "directory for unzipping"); } unzip(zipFile, unzipped); File versionDir = getVersionDirectory(version.getName()); FileUtils.copyDirectory(unzipped, versionDir); } catch (IOException exception) { throw new RuntimeException( "Error installing DynamoDB Local: " + exception.getMessage(), exception ); } finally { monitor.done(); installing.remove(version.getName()); } } /** * @return true if a local test tool process is currently running */ public synchronized boolean isRunning() { return (currentProcess != null); } /** * @return the port to which the current process is bound (or null if no * process is currently running) */ public synchronized Integer getCurrentPort() { if (currentProcess == null) { return null; } return currentProcess.getPort(); } /** * Start the given version of the DynamoDBLocal test tool. * * @param version the version of the test tool to start * @param port the port to bind to */ public synchronized void startVersion(final TestToolVersion version, final int port) { if (!version.isInstalled()) { throw new IllegalStateException("Cannot start a version which is " + "not installed."); } // We should have cleaned this up already, but just to be safe... if (currentProcess != null) { currentProcess.stop(); currentProcess = null; currentlyRunningVersion = null; } IVMInstall jre = getJava7VM(); if (jre == null) { throw new IllegalStateException("No Java 7 VM found!"); } try { File installDirectory = getVersionDirectory(version.getName()); final TestToolProcess process = new TestToolProcess(jre, installDirectory, port); currentProcess = process; currentlyRunningVersion = version; RegionUtils.addLocalService(ServiceAbbreviations.DYNAMODB, "dynamodb", port); // If the process dies for some reason other than that we killed // it, clear out our internal state so the user can start another // instance. process.start(new Runnable() { @Override public void run() { synchronized (TestToolManager.this) { if (process == currentProcess) { cleanUpProcess(); } } } }); } catch (IOException exception) { throw new RuntimeException( "Error starting the DynamoDB Local Test Tool: " + exception.getMessage(), exception ); } } /** * Stop the currently-running DynamoDBLocal process. */ public synchronized void stopVersion() { if (currentProcess != null) { currentProcess.stop(); cleanUpProcess(); } } private void cleanUpProcess() { currentProcess = null; currentlyRunningVersion = null; // Revert to a default port setting. DynamoDBPlugin.getDefault().setDefaultDynamoDBLocalPort(); } /** * Download the given object from S3 to the given file, updating the * given progress monitor periodically. * * @param key The key of the object to download. * @param destination The destination file to download to. * @param monitor The progress monitor to update. */ private void download(final String key, final File destination, final IProgressMonitor monitor) { try { TransferManager tm = getTransferManager(); Download download = tm.download( TEST_TOOL_BUCKET, key, destination ); int totalWork = (int) download.getProgress().getTotalBytesToTransfer(); monitor.beginTask("Downloading DynamoDB Local", totalWork); int worked = 0; while (!download.isDone()) { int bytes = (int) download.getProgress().getBytesTransferred(); if (bytes > worked) { int newWork = bytes - worked; monitor.worked(newWork); worked = bytes; } Thread.sleep(500); } } catch (InterruptedException exception) { Thread.currentThread().interrupt(); throw new RuntimeException( "Interrupted while installing DynamoDB Local", exception ); } catch (AmazonServiceException exception) { throw new RuntimeException( "Error downloading DynamoDB Local: " + exception.getMessage(), exception ); } } /** * Unzip the given file into the given directory. * * @param zipFile The zip file to unzip. * @param unzipped The directory to put the unzipped files into. * @throws IOException on file system error. */ private void unzip(final File zipFile, final File unzipped) throws IOException { try (ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile))) { ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { Path path = new Path(entry.getName()); File dest = new File(unzipped, path.toOSString()); if (entry.isDirectory()) { if (!dest.mkdirs()) { throw new RuntimeException( "Failed to create directory while unzipping" ); } } else { try (FileOutputStream output = new FileOutputStream(dest)) { IOUtils.copy(zip, output); } } } } } /** * Uninstall the given version of the test tool. * * @param version The version to uninstall. */ public void uninstallVersion(final TestToolVersion version) { if (!version.isInstalled()) { return; } try { FileUtils.deleteDirectory( getVersionDirectory(version.getName()) ); } catch (IOException exception) { throw new RuntimeException( "Error while uninstalling DynamoDB Local: " + exception.getMessage(), exception ); } } /** * Load the set of test tool versions from S3, falling back to a cache * on the local disk in case of error. * * @return The loaded test tool version list. */ private List<TestToolVersion> loadVersions() { try { return loadVersionsFromS3(); } catch (IOException exception) { try { return loadVersionsFromLocalCache(); } catch (IOException e) { // No local cache; throw the original exception. throw new RuntimeException( "Error loading DynamoDB Local Test Tool version manifest " + "from Amazon S3. Are you connected to the Internet?", exception ); } } } /** * Loop through the existing set of test tool versions and build a new * list with install states updated to reflect what's actually on disk. * * @param previous The existing list of versions. * @return The updated list of versions. */ private List<TestToolVersion> refreshInstallStates( final List<TestToolVersion> previous ) { List<TestToolVersion> rval = new ArrayList<>(previous.size()); for (TestToolVersion version : previous) { InstallState installState = getInstallState(version.getName()); if (currentlyRunningVersion != null && currentlyRunningVersion.getName() .equals(version.getName())) { installState = InstallState.RUNNING; } else if (installing.contains(version.getName())) { installState = InstallState.INSTALLING; } if (installState == version.getInstallState()) { rval.add(version); } else { rval.add(new TestToolVersion( version.getName(), version.getDescription(), version.getDownloadKey(), installState )); } } return rval; } /** * Attempt to load the manifest file describing available versions of the * test tool from S3. On success, update our local cache of the manifest * file. * * @return The list of versions. * @throws IOException on error. */ private List<TestToolVersion> loadVersionsFromS3() throws IOException { File tempFile = File.createTempFile("dynamodb_local_manifest_", ".xml"); tempFile.delete(); TransferManager manager = getTransferManager(); try { Download download = manager.download( TEST_TOOL_BUCKET, TEST_TOOL_MANIFEST, tempFile ); download.waitForCompletion(); } catch (InterruptedException exception) { Thread.currentThread().interrupt(); throw new RuntimeException( "Interrupted while downloading DynamoDB Local version manifest " + "from S3", exception ); } catch (AmazonServiceException exception) { throw new IOException("Error downloading DynamoDB Local manifest " + "from S3", exception); } List<TestToolVersion> rval = parseManifest(tempFile); try { FileUtils.copyFile(tempFile, getLocalManifestFile()); } catch (IOException exception) { AwsToolkitCore.getDefault().logError( "Error caching manifest file to local disk; do you have " + "write permission to the configured install directory? " + exception.getMessage(), exception); } return rval; } /** * Attempt to load the list of test tool versions from local cache. * * @return The list of test tool versions. * @throws IOException on error. */ private List<TestToolVersion> loadVersionsFromLocalCache() throws IOException { return parseManifest(getLocalManifestFile()); } /** * Parse a manifest file describing a list of test tool versions. * * @param file The file to parse. * @return The parsed list of versions. * @throws IOException on error. */ private List<TestToolVersion> parseManifest(final File file) throws IOException { try (FileInputStream stream = new FileInputStream(file)) { BufferedReader buffer = new BufferedReader( new InputStreamReader(stream) ); ManifestContentHandler handler = new ManifestContentHandler(); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.parse(new InputSource(buffer)); return handler.getResult(); } catch (SAXException exception) { throw new IOException("Error parsing DynamoDB Local manifest file", exception); } } /** * Lazily initialize a transfer manager; keep it around to reuse in the * future if need be. * * @return The transfer manager. */ private synchronized TransferManager getTransferManager() { if (transferManager == null) { AmazonS3 client = AWSClientFactory.getAnonymousS3Client(); transferManager = new TransferManager(client); } return transferManager; } /** * @return The path to the file where we'll store the local manifest cache. * @throws IOException on error. */ private static File getLocalManifestFile() throws IOException { return new File(getInstallDirectory(), "manifest.xml"); } /** * Get the install state of a particular version by looking for the * presence of the DynamoDBLocal.jar file in the corresponding directory. * * @param version The version to check for. * @return The install state of the given version. */ private static InstallState getInstallState(final String version) { try { File versionDir = getVersionDirectory(version); if (!versionDir.exists()) { return InstallState.NOT_INSTALLED; } if (!versionDir.isDirectory()) { return InstallState.NOT_INSTALLED; } File jar = new File(versionDir, "DynamoDBLocal.jar"); if (!jar.exists()) { return InstallState.NOT_INSTALLED; } return InstallState.INSTALLED; } catch (IOException exception) { return InstallState.NOT_INSTALLED; } } /** * Get the path to the directory where we would install the given version * of the test tool. * * @param version The version in question. * @return The path to the install directory. * @throws IOException on error. */ private static File getVersionDirectory(final String version) throws IOException { return new File(getInstallDirectory(), version); } /** * Get the path to the root install directory as configured in the test * tool preference page. * * @return The path to the root install directory. * @throws IOException on error. */ private static File getInstallDirectory() throws IOException { IPreferenceStore preferences = DynamoDBPlugin.getDefault().getPreferenceStore(); String directory = preferences.getString( TestToolPreferencePage.DOWNLOAD_DIRECTORY_PREFERENCE_NAME ); File installDir = new File(directory); if (!installDir.exists()) { if (!installDir.mkdirs()) { throw new IOException("Could not create install directory: " + installDir.getAbsolutePath()); } } else { if (!installDir.isDirectory()) { throw new IOException("Configured install directory is " + "not a directory: " + installDir.getAbsolutePath()); } } return installDir; } /** * SAX handler for the local test tool manifest format. */ private static class ManifestContentHandler extends DefaultHandler { private final List<TestToolVersion> versions = new ArrayList<>(); private StringBuilder currText = new StringBuilder(); private String name; private String description; private String downloadKey; /** * @return The loaded list of versions. */ public List<TestToolVersion> getResult() { return versions; } @Override public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) { if (localName.equals("version")) { // Null these out to be safe. name = null; description = null; downloadKey = null; } } /** {@inheritDoc} */ @Override public void endElement(final String uri, final String localName, final String qName) { if (localName.equals("name")) { name = trim(currText.toString()); currText = new StringBuilder(); } else if (localName.equals("description")) { description = trim(currText.toString()); currText = new StringBuilder(); } else if (localName.equals("key")) { downloadKey = trim(currText.toString()); currText = new StringBuilder(); } else if (localName.equals("version")) { if (name != null || downloadKey != null) { // Skip versions with no name or download key to be safe. versions.add(new TestToolVersion( name, description, downloadKey, getInstallState(name) )); } name = null; description = null; downloadKey = null; } } /** {@inheritDoc} */ @Override public void characters(final char[] ch, final int start, final int length) { currText.append(ch, start, length); } /** * Trim excess whitespace out of the given string. * * @param value The value to trim. * @return The trimmed value. */ private String trim(final String value) { return WHITESPACE.matcher(value.trim()).replaceAll(" "); } } }
7,146
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/testtool/TestToolProcess.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.dynamodb.testtool; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Collection; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.AbstractFileFilter; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.console.IConsole; import org.eclipse.ui.console.IConsoleConstants; import org.eclipse.ui.console.IConsoleManager; import org.eclipse.ui.console.IConsoleView; import org.eclipse.ui.console.MessageConsole; import org.eclipse.ui.console.MessageConsoleStream; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; /** * A DynamoDB Local Test Tool process. */ public class TestToolProcess { private final IVMInstall jre; private final File installDirectory; private final int port; private final Thread shutdownHook = new Thread() { @Override public void run() { TestToolProcess.this.stopProcess(); } }; private Process process; /** * Create a new {@code TestToolProcess}. * * @param jre the JRE to use to run DynamoDBLocal * @param installDirectory the root install directory for DynamoDBLocal * @param port the TCP port to bind to */ public TestToolProcess(final IVMInstall jre, final File installDirectory, final int port) { this.jre = jre; this.installDirectory = installDirectory; this.port = port; } /** * @return the port that this DynamoDBLocal process is listening on */ public int getPort() { return port; } /** * Start the DynamoDBLocal process. * * @param onExitAction optional action to be executed when the process * exits * @throws IOException if starting the process fails */ public synchronized void start(final Runnable onExitAction) throws IOException { if (process != null) { throw new IllegalStateException("Already started!"); } ProcessBuilder builder = new ProcessBuilder(); builder.directory(installDirectory); builder.command( jre.getInstallLocation().getAbsolutePath().concat("/bin/java"), "-Djava.library.path=".concat(findLibraryDirectory().getAbsolutePath()), "-jar", "DynamoDBLocal.jar", "--port", Integer.toString(port) ); // Drop STDERR into STDOUT so we can handle them together. builder.redirectErrorStream(true); // Register a shutdown hook to kill DynamoDBLocal if Eclipse exits. Runtime.getRuntime().addShutdownHook(shutdownHook); // Start the DynamoDBLocal process. process = builder.start(); // Start a background thread to read any output from DynamoDBLocal // and dump it to an IConsole. new ConsoleOutputLogger(process.getInputStream(), onExitAction) .start(); } /** * Searches within the install directory for the native libraries required * by DyanmoDB Local (i.e. SQLite) and returns the directory containing the * native libraries. * * @return The directory within the install directory where native libraries * were found; otherwise, if no native libraries are found, the * install directory is returned. */ private File findLibraryDirectory() { // Mac and Linux libraries start with "libsqlite4java-" so // use that pattern to identify the library directory IOFileFilter fileFilter = new AbstractFileFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("libsqlite4java-"); } }; Collection<File> files = FileUtils.listFiles(installDirectory, fileFilter, TrueFileFilter.INSTANCE); // Log a warning if we can't identify the library directory, // and then just try to use the install directory if (files == null || files.isEmpty()) { Status status = new Status(IStatus.WARNING, DynamoDBPlugin.PLUGIN_ID, "Unable to find DynamoDB Local native libraries in " + installDirectory); AwsToolkitCore.getDefault().getLog().log(status); return installDirectory; } return files.iterator().next().getParentFile(); } /** * Stop the DynamoDBLocal process and deregister the shutdown hook. */ public synchronized void stop() { stopProcess(); Runtime.getRuntime().removeShutdownHook(shutdownHook); } /** * Internal helper method to actually stop the DynamoDBLocal process. */ private void stopProcess() { if (process != null) { process.destroy(); process = null; } } /** * A background thread that reads output from the DynamoDBLocal process * and pumps it to a console window. */ private static class ConsoleOutputLogger extends Thread { private final BufferedReader input; private final Runnable onExitAction; /** * Create a new logger. * * @param stream the input stream to read from * @param onExitaction an optional action to be run when the process * exits */ public ConsoleOutputLogger(final InputStream stream, final Runnable onExitAction) { this.input = new BufferedReader(new InputStreamReader(stream)); this.onExitAction = onExitAction; super.setDaemon(true); super.setName("DynamoDBLocal Console Output Logger"); } @Override public void run() { MessageConsole console = findConsole(); displayConsole(console); MessageConsoleStream stream = console.newMessageStream(); try { while (true) { String line = input.readLine(); if (line == null) { stream.println("*** DynamoDB Local Exited ***"); break; } stream.println(line); } } catch (IOException exception) { stream.println("Exception reading the output of " + "DynamoDB Local: " + exception.toString()); } finally { try { input.close(); } catch (IOException exception) { exception.printStackTrace(); } try { stream.close(); } catch (IOException exception) { exception.printStackTrace(); } if (onExitAction != null) { onExitAction.run(); } } } /** * Find or create a new console window for DynamoDBLocal's output. * * @return the console to log output to */ private MessageConsole findConsole() { ConsolePlugin plugin = ConsolePlugin.getDefault(); IConsoleManager manager = plugin.getConsoleManager(); IConsole[] existing = manager.getConsoles(); for (int i = 0; i < existing.length; ++i) { if (existing[i].getName().equals("DynamoDB Local")) { return (MessageConsole) existing[i]; } } MessageConsole console = new MessageConsole("DynamoDB Local", null); manager.addConsoles(new IConsole[] { console }); return console; } /** * Display the given console if it's not already visible. * * @param console the console to display */ private void displayConsole(final IConsole console) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage(); try { IConsoleView view = (IConsoleView) page.showView(IConsoleConstants.ID_CONSOLE_VIEW); view.display(console); } catch (PartInitException exception) { // Is there something more intelligent we should be // doing with this? exception.printStackTrace(); } } }); } } }
7,147
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/testtool/TestToolVersion.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.dynamodb.testtool; public class TestToolVersion { public static enum InstallState { NOT_INSTALLED, INSTALLING, INSTALLED, RUNNING } private final String name; private final String description; private final String downloadKey; private final InstallState installState; public TestToolVersion(final String name, final String description, final String downloadKey, final InstallState installState) { if (name == null) { throw new NullPointerException("name cannot be null"); } if (downloadKey == null) { throw new NullPointerException("downloadKey cannot be null"); } if (installState == null) { throw new NullPointerException("installState cannot be null"); } this.name = name; this.description = (description == null ? "" : description); this.downloadKey = downloadKey; this.installState = installState; } public String getName() { return name; } public String getDescription() { return description; } public String getDownloadKey() { return downloadKey; } public boolean isInstalled() { return (installState == InstallState.INSTALLED); } public boolean isInstalling() { return (installState == InstallState.INSTALLING); } public boolean isRunning() { return (installState == InstallState.RUNNING); } public InstallState getInstallState() { return installState; } @Override public String toString() { return "DynamoDB_Local_" + name; } }
7,148
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/testtool/StartTestToolConfigurationWizardPage.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.dynamodb.testtool; 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.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.preference.IPreferenceStore; 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.core.AwsToolkitCore; import com.amazonaws.eclipse.core.ui.wizards.ErrorDecorator; import com.amazonaws.eclipse.core.validator.IntegerRangeValidator; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.eclipse.dynamodb.preferences.TestToolPreferencePage; /** * An (optional) wizard page that lets the user set up additional configuration * for the test tool instance they're about to launch. For now, that's just * the TCP port it will listen on. */ public class StartTestToolConfigurationWizardPage extends WizardPage { private final DataBindingContext context = new DataBindingContext(); private final IObservableValue portValue = new WritableValue(); private Text portInput; /** * Create a new instance. */ public StartTestToolConfigurationWizardPage() { super("Configure the DynamoDB Local Test Tool"); super.setMessage("Configure the DynamoDB Local Test Tool"); super.setImageDescriptor( AwsToolkitCore.getDefault() .getImageRegistry() .getDescriptor("dynamodb-service") ); } /** * @return the chosen port to listen on */ public int getPort() { return Integer.parseInt((String) portValue.getValue()); } /** * Create the wizard page's controls. * * @param parent the parent composite to hang the controls on */ @Override public void createControl(final Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); composite.setLayout(new GridLayout(2, false)); Label label = new Label(composite, SWT.NONE); label.setText("Port: "); portInput = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(portInput); // TODO: Would be nice to drive this off of the manifest.xml for the // chosen version, in case future versions of the test tool support // additional options. bindInputs(); IPreferenceStore preferences = DynamoDBPlugin.getDefault().getPreferenceStore(); if (preferences.contains(TestToolPreferencePage .DEFAULT_PORT_PREFERENCE_NAME)) { portValue.setValue(Integer.toString( preferences.getInt(TestToolPreferencePage .DEFAULT_PORT_PREFERENCE_NAME) )); context.updateTargets(); } setControl(composite); } /** * Bind the UI to our internal model and wire up a validator to make sure * the user has input valid value(s). */ private void bindInputs() { IObservableValue observable = SWTObservables.observeText(portInput, SWT.Modify); context.bindValue(observable, portValue); context.addValidationStatusProvider( new ChainValidator<String>( observable, new PortValidator() ) ); final AggregateValidationStatus aggregator = new AggregateValidationStatus(context, AggregateValidationStatus.MAX_SEVERITY); aggregator.addChangeListener(new IChangeListener() { @Override public void handleChange(final ChangeEvent event) { Object value = aggregator.getValue(); if (!(value instanceof IStatus)) { return; } IStatus status = (IStatus) value; setPageComplete(status.isOK()); } }); ErrorDecorator.bind(portInput, aggregator); } /** * A validator that ensures the input is a valid port number. * @deprecated for {@link IntegerRangeValidator} */ private static class PortValidator implements IValidator { @Override public IStatus validate(final Object value) { if (!(value instanceof String)) { return ValidationStatus.error("No port specified"); } int port; try { port = Integer.parseInt((String) value); } catch (NumberFormatException exception) { return ValidationStatus.error( "Port must be an integer between 1 and 35535"); } if (port <= 0 || port > 0xFFFF) { return ValidationStatus.error( "Port must be an integer between 1 and 35535"); } return ValidationStatus.ok(); } } }
7,149
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/testtool/StartTestToolWizard.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.dynamodb.testtool; import org.eclipse.jface.wizard.Wizard; /** * A wizard that starts an instance of the DynamoDBLocal Test Tool. */ public class StartTestToolWizard extends Wizard { private StartTestToolPickVersionWizardPage versionPage; private StartTestToolConfigurationWizardPage portPage; /** * Create the wizard. */ public StartTestToolWizard() { super.setNeedsProgressMonitor(false); super.setWindowTitle("Start the DynamoDB Local Test Tool"); } @Override public void addPages() { // TODO: Could we use an initial page describing what the local test // tool is? versionPage = new StartTestToolPickVersionWizardPage(); addPage(versionPage); portPage = new StartTestToolConfigurationWizardPage(); addPage(portPage); } @Override public boolean performFinish() { TestToolManager.INSTANCE.startVersion( versionPage.getSelectedVersion(), portPage.getPort() ); return true; } }
7,150
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/testtool/TestToolVersionTable.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.dynamodb.testtool; import java.util.Collection; import java.util.LinkedList; import java.util.List; 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.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.databinding.viewers.ViewersObservables; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ProgressBar; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.eclipse.dynamodb.testtool.TestToolVersion.InstallState; import com.amazonaws.eclipse.explorer.AwsAction; /** * A table that displays the set of available DynamoDB Local Test Tool * versions and allows you to install or uninstall them. */ public class TestToolVersionTable extends Composite { /** * Background job that checks for changes to the list of test tool * versions and updates the table. */ private final Job updateJob = new Job("DynamoDB Local Test Tool Update") { @Override protected IStatus run(final IProgressMonitor monitor) { setInput(TestToolManager.INSTANCE.getAllVersions()); return Status.OK_STATUS; } }; /** * Background job that installs a particular version of the test tool. */ private class InstallJob extends Job { private final TestToolVersion version; /** * @param version The version of the test tool to install. */ public InstallJob(final TestToolVersion version) { super("DynamoDB Local Test Tool Install"); this.version = version; } /** {@inheritDoc} */ @Override protected IStatus run(final IProgressMonitor monitor) { // Mark the version as currently being installed so we disable // the 'install' button. TestToolManager.INSTANCE.markInstalling(version); checkForUpdates(); // Actually do the install, updating the progress bar as we go. try { TestToolManager.INSTANCE .installVersion(version, progressMonitor); } finally { checkForUpdates(); } return Status.OK_STATUS; } } /** * A background job that uninstalls a particular version of the test tool. */ private class UninstallJob extends Job { private final TestToolVersion version; /** * @param version The version of the test tool to uninstall. */ public UninstallJob(final TestToolVersion version) { super("DynamoDB Local Test Tool Uninstall"); this.version = version; } /** {@inheritDoc} */ @Override protected IStatus run(final IProgressMonitor monitor) { TestToolManager.INSTANCE.uninstallVersion(version); checkForUpdates(); return Status.OK_STATUS; } } private final Collection<Font> fonts = new LinkedList<>(); private TreeViewer viewer; private ToolBarManager toolbar; private CustomProgressMonitor progressMonitor; private Group detailsGroup; private Label versionText; private Label descriptionText; private Action installAction; private Action uninstallAction; /** * @param parent The parent composite to attach to. */ public TestToolVersionTable(final Composite parent) { super(parent, SWT.NONE); GridLayout layout = new GridLayout(1, false); setLayout(layout); createToolbar(); createViewer(); createDetailsGroup(); createActions(); hookToolbar(); hookContextMenu(); checkForUpdates(); } /** * @return The currently selected test tool version (or null). */ public TestToolVersion getSelection() { StructuredSelection selection = (StructuredSelection) viewer.getSelection(); return (TestToolVersion) selection.getFirstElement(); } /** * @return an observable that tracks the current selection */ public IObservableValue getObservableSelection() { return ViewersObservables.observeSingleSelection(viewer); } /** {@inheritDoc} */ @Override public void dispose() { for (Font font : fonts) { font.dispose(); } super.dispose(); } /** * Create the toolbar, with install and uninstall buttons and an initially * hidden progress bar to track install status. */ private void createToolbar() { // Bind to the top of wherever we end up. Composite wrapper = new Composite(this, SWT.NONE); wrapper.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); wrapper.setLayout(new GridLayout(2, false)); toolbar = new CustomToolBarManager(); // Toolbar on the left. Control control = toolbar.createControl(wrapper); control.setLayoutData( new GridData(SWT.LEFT, SWT.CENTER, false, false) ); // Progress bar on the right. ProgressBar progressBar = new ProgressBar(wrapper, SWT.NONE); progressBar.setLayoutData( new GridData(SWT.RIGHT, SWT.CENTER, true, false) ); progressBar.setVisible(false); progressMonitor = new CustomProgressMonitor(progressBar); } /** * Create the actual table view displaying the list of selectable test * tool versions. */ private void createViewer() { // Grab any leftover space in the middle. Composite wrapper = new Composite(this, SWT.NONE); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); data.heightHint = 200; wrapper.setLayoutData(data); TreeColumnLayout layout = new TreeColumnLayout(); wrapper.setLayout(layout); viewer = new TreeViewer( wrapper, SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE ); TestToolVersionProvider provider = new TestToolVersionProvider(); viewer.setContentProvider(provider); viewer.setLabelProvider(provider); viewer.setComparator(new VersionComparator()); viewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { onSelectionChanged(); } }); Tree tree = viewer.getTree(); tree.setHeaderVisible(true); TreeColumn versionColumn = new TreeColumn(tree, SWT.LEFT); versionColumn.setText("Version"); layout.setColumnData(versionColumn, new ColumnWeightData(75)); TreeColumn installColumn = new TreeColumn(tree, SWT.CENTER); installColumn.setText("Installed?"); layout.setColumnData(installColumn, new ColumnWeightData(25)); } /** * Create the (initially hidden) details group, which shows a longer text * description of the currently-selected version. */ private void createDetailsGroup() { detailsGroup = new Group(this, SWT.NONE); detailsGroup.setText("Details"); detailsGroup.setLayout(new GridLayout(2, false)); detailsGroup.setVisible(false); // Pin to the bottom to allow the table control to have as much space // as it wants. GridData data = new GridData(SWT.FILL, SWT.BOTTOM, true, false); data.widthHint = 300; detailsGroup.setLayoutData(data); Label version = new Label(detailsGroup, SWT.TOP); version.setText("Version: "); makeBold(version); versionText = new Label(detailsGroup, SWT.WRAP); Label description = new Label(detailsGroup, SWT.TOP); description.setText("Description: "); makeBold(description); descriptionText = new Label(detailsGroup, SWT.WRAP); data = new GridData(SWT.FILL, SWT.FILL, true, true); data.widthHint = 300; descriptionText.setLayoutData(data); } /** * Make the given label bold. * * @param label The label to embolden. */ private void makeBold(final Label label) { FontData[] fontData = label.getFont().getFontData(); fontData[0].setStyle(SWT.BOLD); Font font = new Font(getDisplay(), fontData[0]); fonts.add(font); label.setFont(font); } /** * Create the install and uninstall actions for the toolbar and context * menu. */ private void createActions() { installAction = new AwsAction(AwsToolkitMetricType.DYNAMODB_INSTALL_TEST_TOOL) { @Override protected void doRun() { new InstallJob(getSelection()).schedule(); actionFinished(); } }; installAction.setText("Install"); installAction.setToolTipText("Install the selected version."); installAction.setImageDescriptor( DynamoDBPlugin.getDefault() .getImageRegistry() .getDescriptor("add") ); installAction.setEnabled(false); uninstallAction = new AwsAction(AwsToolkitMetricType.DYNAMODB_UNINSTALL_TEST_TOOL) { @Override protected void doRun() { new UninstallJob(getSelection()).schedule(); actionFinished(); } }; uninstallAction.setText("Uninstall"); uninstallAction.setToolTipText("Uninstall the selected version."); uninstallAction.setImageDescriptor( DynamoDBPlugin.getDefault() .getImageRegistry() .getDescriptor("remove") ); uninstallAction.setEnabled(false); } /** * Hook the actions created above into the toolbar. */ private void hookToolbar() { toolbar.add(installAction); toolbar.add(new Separator()); toolbar.add(uninstallAction); toolbar.update(true); } /** * Hook the actions created above into the context menu for the table. */ private void hookContextMenu() { MenuManager manager = new MenuManager("#PopupMenu"); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { manager.add(installAction); manager.add(uninstallAction); } }); Menu menu = manager.createContextMenu(viewer.getControl()); viewer.getControl().setMenu(menu); manager.createContextMenu(viewer.getControl()); } /** * Check for changes to the list of test tool versions. */ private void checkForUpdates() { updateJob.schedule(); } /** * Handler callback for when the selected version changes. Enable or * disable the install/uninstall actions as appropriate, and update the * details group. */ private void onSelectionChanged() { TestToolVersion version = getSelection(); if (version == null) { installAction.setEnabled(false); uninstallAction.setEnabled(false); detailsGroup.setVisible(false); } else { installAction.setEnabled( version.getInstallState() == InstallState.NOT_INSTALLED ); uninstallAction.setEnabled( version.getInstallState() == InstallState.INSTALLED ); versionText.setText(version.getName()); descriptionText.setText(version.getDescription()); detailsGroup.setVisible(true); detailsGroup.pack(); } toolbar.update(false); } /** * Set the list of test tool versions to display in the table. * * @param versions The list of versions. */ private void setInput(final List<TestToolVersion> versions) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { _setInput(versions); } }); } /** * Helper for setInput() that MUST be run on the UI thread. */ private void _setInput(final List<TestToolVersion> versions) { TestToolVersion previous = getSelection(); viewer.setInput(versions); if (previous != null) { Tree tree = viewer.getTree(); for (int i = 0; i < tree.getItemCount(); ++i) { TreeItem item = tree.getItem(i); TestToolVersion version = (TestToolVersion) item.getData(); if (previous.getName().equals(version.getName())) { tree.select(item); tree.notifyListeners(SWT.Selection, null); break; } } } } /** * A content and label provider for the test tool table. */ private class TestToolVersionProvider extends LabelProvider implements ITreeContentProvider, ITableLabelProvider { private List<TestToolVersion> versions; /** {@inheritDoc} */ @Override public Object[] getElements(final Object inputElement) { if (versions == null) { return null; } return versions.toArray(); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { versions = (List<TestToolVersion>) newInput; } /** {@inheritDoc} */ @Override public Image getColumnImage(final Object element, final int columnIndex) { return null; } /** {@inheritDoc} */ @Override public String getColumnText(final Object element, final int columnIndex) { if (!(element instanceof TestToolVersion)) { return "???"; } TestToolVersion version = (TestToolVersion) element; switch (columnIndex) { case 0: return version.getName(); case 1: if (version.isRunning()) { return "Running..."; } if (version.isInstalled()) { return "Yes"; } if (version.isInstalling()) { return "Installing..."; } return ""; default: return "???"; } } /** {@inheritDoc} */ @Override public Object[] getChildren(final Object parentElement) { return new Object[0]; } /** {@inheritDoc} */ @Override public Object getParent(final Object element) { return null; } /** {@inheritDoc} */ @Override public boolean hasChildren(final Object element) { return false; } } /** * Sort versions in reverse alphabetical order (which, since version * numbers are dates, is also conveniently reverse chronological order). */ private class VersionComparator extends ViewerComparator { /** {@inheritDoc} */ @Override public int compare(final Viewer viewer, final Object e1, final Object e2) { if (!(e1 instanceof TestToolVersion)) { return 0; } if (!(e2 instanceof TestToolVersion)) { return 0; } TestToolVersion v1 = (TestToolVersion) e1; TestToolVersion v2 = (TestToolVersion) e2; return v2.getName().compareTo(v1.getName()); } } /** * A Progress Monitor that updates a ProgressBar as the test tool is * installed. */ private static class CustomProgressMonitor implements IProgressMonitor { private final ProgressBar progressBar; /** * @param progressBar The progress bar to update. */ public CustomProgressMonitor(final ProgressBar progressBar) { this.progressBar = progressBar; } /** {@inheritDoc} */ @Override public void beginTask(final String name, final int totalWork) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { progressBar.setMinimum(0); progressBar.setMaximum(totalWork); progressBar.setSelection(0); progressBar.setToolTipText(name); progressBar.setVisible(true); } }); } /** {@inheritDoc} */ @Override public void worked(final int work) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { progressBar.setSelection( progressBar.getSelection() + work ); } }); } /** {@inheritDoc} */ @Override public void done() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { progressBar.setVisible(false); } }); } /** {@inheritDoc} */ @Override public void internalWorked(double arg0) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @Override public boolean isCanceled() { return false; } /** {@inheritDoc} */ @Override public void setCanceled(boolean arg0) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @Override public void setTaskName(String arg0) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @Override public void subTask(String arg0) { throw new UnsupportedOperationException(); } } /** * A toolbar manager that forces text mode on all actions added to it. */ private static class CustomToolBarManager extends ToolBarManager { public CustomToolBarManager() { super(SWT.FLAT | SWT.RIGHT); } /** {@inheritDoc} */ @Override public void add(final IAction action) { ActionContributionItem item = new ActionContributionItem(action); item.setMode(ActionContributionItem.MODE_FORCE_TEXT); super.add(item); } } }
7,151
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/AttributeValueInputDialog.java
package com.amazonaws.eclipse.dynamodb.editor; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; 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.Label; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; /** * A generic class that includes basic dialog template and value validation. */ public class AttributeValueInputDialog extends MessageDialog { final List<String> attributeNames; final Map<String, Integer> attributeDataTypes; final Map<String, String> attributeValues; final boolean cancelable; Label valueValidationWarningLabel; public AttributeValueInputDialog(final String dialogTitle, final String dialogMessage, final boolean cancelable, final List<String> attributeNames, final Map<String, Integer> attributeDataTypes, final Map<String, String> initialTextualValue) { /* Use the current active shell and the default dialog template. */ super(Display.getCurrent().getActiveShell(), dialogTitle, AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON), dialogMessage, MessageDialog.NONE, cancelable ? new String[] {"OK", "Cancel"} : new String[] {"OK"}, 0); /* Hide the title bar which includes the close button */ if ( !cancelable ) { setShellStyle(SWT.NONE); } this.cancelable = cancelable; /* Defensive hard copy */ List<String> attributeNamesCopy = new LinkedList<>(); attributeNamesCopy.addAll(attributeNames); this.attributeNames = Collections.unmodifiableList(attributeNamesCopy); Map<String, Integer> attributeDataTypesCopy = new HashMap<>(); attributeDataTypesCopy.putAll(attributeDataTypes); this.attributeDataTypes = Collections.unmodifiableMap(attributeDataTypesCopy); /* Set initial values */ this.attributeValues = new HashMap<>(); if ( null != initialTextualValue ) { this.attributeValues.putAll(initialTextualValue); } /* Empty string for attribute not provided with initial value. */ for (String attributeName : attributeNames) { if ( !attributeValues.containsKey(attributeName) ) { attributeValues.put(attributeName, ""); } } } @Override protected void handleShellCloseEvent() { if ( !cancelable ) { /* Suppress colse event */ return; } else { super.handleShellCloseEvent(); } }; @Override protected Control createCustomArea(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(comp); GridDataFactory.fillDefaults().grab(true, true).applyTo(comp); for (final String attributeName : attributeNames) { Label nameLabel = new Label(comp, SWT.READ_ONLY); nameLabel.setText(attributeName + ":"); final Text inputValueText = new Text(comp, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(inputValueText); /* Initial value */ inputValueText.setText(attributeValues.get(attributeName)); /* Modify listener that updates the UI and the underlying data model. */ inputValueText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { attributeValues.put(attributeName, inputValueText.getText()); updateDialogUI(); } }); } new Label(comp, SWT.NONE); valueValidationWarningLabel = new Label(comp, SWT.WRAP); valueValidationWarningLabel.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_RED)); GridDataFactory.fillDefaults().grab(true, false).applyTo(valueValidationWarningLabel); updateDialogUI(); return comp; } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); updateDialogUI(); } public String getInputValue(String attributeName) { return attributeValues.get(attributeName); } private void updateDialogUI() { if ( getButton(0) == null ) return; /* Check whether we should show validation warning. */ boolean showValueValidationWarning = false; for (String attributeName : attributeNames) { if ( attributeValues.get(attributeName) != null && !attributeValues.get(attributeName).isEmpty() ) { /* Only shows the warning when at least one input is not empty. */ showValueValidationWarning = true; break; } } /* Validate each attribute value. */ for (String attributeName : attributeNames) { String currentValue = attributeValues.get(attributeName); int dataType = attributeDataTypes.get(attributeName); if ( !AttributeValueUtil.validateScalarAttributeInput(currentValue, dataType, false) ) { if ( showValueValidationWarning ) { valueValidationWarningLabel.setText(AttributeValueUtil .getScalarAttributeValidationWarning( attributeName, dataType)); } else { valueValidationWarningLabel.setText(""); } getButton(0).setEnabled(false); return; } } /* If all values are valid. */ getButton(0).setEnabled(true); valueValidationWarningLabel.setText(""); return; } }
7,152
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/DynamoDBTableEditor.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.dynamodb.editor; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueEditor.NUMBER; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueEditor.STRING; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.N; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.NS; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.S; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.SS; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.format; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.getDataType; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.getValuesFromAttribute; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.setAttribute; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.core.commands.IHandler; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; 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.action.ToolBarManager; import org.eclipse.jface.commands.ActionHandler; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; 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.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Sash; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.statushandlers.StatusManager; import com.amazonaws.AmazonClientException; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.core.ui.AbstractTableLabelProvider; import com.amazonaws.eclipse.dynamodb.AbstractAddNewAttributeDialog; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.AttributeAction; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.DeleteItemRequest; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.DescribeTableResult; import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import com.amazonaws.services.dynamodbv2.model.ScanRequest; import com.amazonaws.services.dynamodbv2.model.ScanResult; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest; /** * Scan editor for DynamoDB tables. */ public class DynamoDBTableEditor extends EditorPart { private static final String[] exportExtensions = new String[] { "*.csv" }; /* * SWT editor glue */ public static final String ID = "com.amazonaws.eclipse.dynamodb.editor.tableEditor"; private TableEditorInput tableEditorInput; private boolean dirty; /* * Large-scale UI elements */ private ToolBarManager toolBarManager; private ToolBar toolBar; private TableViewer viewer; private ContentProvider contentProvider; /* * Data model for UI: list of scan conditions assembled by the user and a * set of items they've edited, added and deleted. */ private final List<ScanConditionRow> scanConditions = new LinkedList<>(); private final EditedItems editedItems = new EditedItems(); private final Collection<Map<String, AttributeValue>> deletedItems = new LinkedList<>(); private final Collection<Map<String, AttributeValue>> addedItems = new LinkedList<>(); /* * Table info that we fetch and store */ private KeySchemaWithAttributeType tableKey; final Set<String> knownAttributes = new HashSet<>(); private ScanResult scanResult = new ScanResult(); /* * Actions to enable and disable */ private Action runScanAction; private Action saveAction; private Action nextPageResultsAction; private Action exportAsCSVAction; private Action addNewAttributeAction; @Override public void doSave(IProgressMonitor monitor) { monitor.beginTask("Saving changes", editedItems.size() + deletedItems.size()); try{ AmazonDynamoDB dynamoDBClient = AwsToolkitCore.getClientFactory(tableEditorInput.getAccountId()) .getDynamoDBV2Client(); /* * Save all edited items, only touching edited attributes. */ if ( !editedItems.isEmpty() ) { for ( Iterator<Entry<Map<String, AttributeValue>, EditedItem>> iter = editedItems.iterator(); iter.hasNext(); ) { Entry<Map<String, AttributeValue>, EditedItem> editedItem = iter.next(); try { /* * Due to a bug in Dynamo, updateItem will not create a * new item when only the key is specified. Therefore, * we need two code paths here, as in * DynamoDBMapper.save(). */ if ( editedItem.getValue().getEditedAttributes().isEmpty() ) { PutItemRequest rq = new PutItemRequest().withTableName(tableEditorInput.getTableName()); rq.setItem(editedItem.getValue().getAttributes()); Map<String, ExpectedAttributeValue> expected = new HashMap<>(); for ( String attr : editedItem.getValue().getAttributes().keySet() ) { expected.put(attr, new ExpectedAttributeValue().withExists(false)); } rq.setExpected(expected); dynamoDBClient.putItem(rq); } else { UpdateItemRequest rq = new UpdateItemRequest().withTableName(tableEditorInput .getTableName()); rq.setKey(editedItem.getKey()); Map<String, AttributeValueUpdate> values = new HashMap<>(); for ( String attributeName : editedItem.getValue().getEditedAttributes() ) { AttributeValueUpdate update = new AttributeValueUpdate(); AttributeValue attributeValue = editedItem.getValue().getAttributes() .get(attributeName); if ( attributeValue == null ) { update.setAction(AttributeAction.DELETE); } else { update.setAction(AttributeAction.PUT); update.setValue(attributeValue); } values.put(attributeName, update); } rq.setAttributeUpdates(values); dynamoDBClient.updateItem(rq); } for ( int col = 0; col < viewer.getTable().getColumnCount(); col++ ) { editedItem.getValue().getTableItem() .setForeground(col, Display.getDefault().getSystemColor(SWT.COLOR_BLACK)); } iter.remove(); monitor.worked(1); } catch ( AmazonClientException e ) { StatusManager.getManager().handle( new Status(IStatus.ERROR, DynamoDBPlugin.PLUGIN_ID, "Error saving item with key " + editedItem.getKey() + ": " + e.getMessage()), StatusManager.SHOW); return; } } } /* * Delete all deleted items. */ if ( !deletedItems.isEmpty() ) { for ( Iterator<Map<String, AttributeValue>> iter = deletedItems.iterator(); iter.hasNext(); ) { Map<String, AttributeValue> deletedItem = iter.next(); try { dynamoDBClient.deleteItem(new DeleteItemRequest() .withTableName(tableEditorInput.getTableName()).withKey(deletedItem)); } catch ( AmazonClientException e ) { StatusManager.getManager().handle( new Status(IStatus.ERROR, DynamoDBPlugin.PLUGIN_ID, "Error deleting item with key " + deletedItem + ": " + e.getMessage()), StatusManager.SHOW); return; } iter.remove(); monitor.worked(1); } } /* * Exception handling: if we fail to execute any action above, the * editor is left in a sane state -- we clean up edited state as we * make each service call, so all we have to do is notify of the * exception and return without updating the editor's dirty state. */ } finally { monitor.done(); } dirty = false; this.saveAction.setEnabled(false); firePropertyChange(PROP_DIRTY); } @Override public void doSaveAs() { // unsupported } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); this.tableEditorInput = (TableEditorInput) input; setPartName(input.getName()); } @Override public boolean isDirty() { return dirty; } private void markDirty() { dirty = true; saveAction.setEnabled(true); firePropertyChange(PROP_DIRTY); } @Override public boolean isSaveAsAllowed() { return false; } @Override public void createPartControl(Composite composite) { composite.setLayout(new FormLayout()); // Create the sash first, so the other controls // can be attached to it. final Sash sash = new Sash(composite, SWT.HORIZONTAL); FormData data = new FormData(); // Initial position is a quarter of the way down the composite data.top = new FormAttachment(25, 0); // And filling 100% of horizontal space data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); sash.setLayoutData(data); sash.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent event) { // Move the sash to its new position and redraw it ((FormData) sash.getLayoutData()).top = new FormAttachment(0, event.y); sash.getParent().layout(); } }); this.toolBarManager = new ToolBarManager(SWT.LEFT); this.toolBar = this.toolBarManager.createControl(composite); Composite scanEditor = createScanEditor(composite); data = new FormData(); data.top = new FormAttachment(0, 0); data.bottom = new FormAttachment(scanEditor, 0); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); this.toolBar.setLayoutData(data); data = new FormData(); data.top = new FormAttachment(this.toolBar, 0); data.bottom = new FormAttachment(sash, 0); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); scanEditor.setLayoutData(data); // Results table is attached to the top of the sash Composite resultsComposite = new Composite(composite, SWT.BORDER); data = new FormData(); data.top = new FormAttachment(sash, 0); data.bottom = new FormAttachment(100, 0); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); resultsComposite.setLayoutData(data); createResultsTable(resultsComposite); createActions(); // initialize the table with results runScan(); } /** * Creates the composite to edit scan requests */ private Composite createScanEditor(Composite composite) { final Composite scanEditor = new Composite(composite, SWT.None); GridLayoutFactory.fillDefaults().applyTo(scanEditor); final Button addCondition = new Button(scanEditor, SWT.PUSH); addCondition.setToolTipText("Add scan condition"); addCondition.setText("Add scan condition"); addCondition.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD)); GridDataFactory.swtDefaults().indent(5, 0).applyTo(addCondition); // Selection listener creates a new row in the editor, then moves the // button below this new row. addCondition.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { scanEditor.getParent().setRedraw(false); ScanConditionRow scanConditionRow = new ScanConditionRow(scanEditor, knownAttributes); scanConditions.add(scanConditionRow); addCondition.moveBelow(scanConditionRow); scanEditor.pack(true); scanEditor.getParent().layout(true); scanEditor.getParent().setRedraw(true); } }); return scanEditor; } private void createActions() { runScanAction = new AwsAction(AwsToolkitMetricType.EXPLORER_DYNAMODB_RUN_SCAN) { @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_START); } @Override public String getText() { return "Run scan"; } @Override public String getToolTipText() { return getText(); } @Override protected void doRun() { runScan(); actionFinished(); } @Override public String getActionDefinitionId() { return "com.amazonaws.eclipse.dynamodb.editor.runScan"; } }; IHandler handler = new ActionHandler(runScanAction); IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class); handlerService.activateHandler(runScanAction.getActionDefinitionId(), handler); saveAction = new AwsAction(AwsToolkitMetricType.EXPLORER_DYNAMODB_SAVE) { @Override public ImageDescriptor getImageDescriptor() { return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_ETOOL_SAVE_EDIT); } @Override public String getText() { return "Save changes to Dynamo"; } @Override protected void doRun() { getEditorSite().getPage().saveEditor(DynamoDBTableEditor.this, false); } @Override public String getActionDefinitionId() { return "org.eclipse.ui.file.save"; } }; handlerService.activateHandler(saveAction.getActionDefinitionId(), new ActionHandler(saveAction)); nextPageResultsAction = new AwsAction() { @Override public ImageDescriptor getImageDescriptor() { return DynamoDBPlugin.getDefault().getImageRegistry().getDescriptor(DynamoDBPlugin.IMAGE_NEXT_RESULTS); } @Override public String getText() { return "Next page of results"; } @Override protected void doRun() { getNextPageResults(); actionFinished(); } }; exportAsCSVAction = new AwsAction(AwsToolkitMetricType.EXPLORER_DYNAMODB_EXPORT_AS_CSV) { @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_EXPORT); } @Override public String getText() { return "Export as CSV"; } @Override protected void doRun() { FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); dialog.setOverwrite(true); dialog.setFilterExtensions(exportExtensions); String csvFile = dialog.open(); if (csvFile != null) { writeCsvFile(csvFile); } else { actionCanceled(); } actionFinished(); } private void writeCsvFile(final String csvFile) { try { // truncate file before writing try (RandomAccessFile raf = new RandomAccessFile(new File(csvFile), "rw")) { raf.setLength(0L); } List<Map<String, AttributeValue>> items = new LinkedList<>(); for ( TableItem tableItem : viewer.getTable().getItems() ) { @SuppressWarnings("unchecked") Map<String, AttributeValue> e = (Map<String, AttributeValue>) tableItem.getData(); items.add(e); } try (BufferedWriter out = new BufferedWriter(new FileWriter(csvFile))) { boolean seenOne = false; for (String col : contentProvider.getColumns()) { if ( seenOne ) { out.write(","); } else { seenOne = true; } out.write(col); } out.write("\n"); for ( Map<String, AttributeValue> item : items ) { seenOne = false; for (String col : contentProvider.getColumns()) { if (seenOne) { out.write(","); } else { seenOne = true; } AttributeValue values = item.get(col); if (values != null) { String value = format(values); // For csv files, we need to quote all values and escape all quotes value = value.replaceAll("\"", "\"\""); value = "\"" + value + "\""; out.write(value); } } out.write("\n"); } } actionSucceeded(); } catch (Exception e) { actionFailed(); AwsToolkitCore.getDefault().logError("Couldn't save CSV file", e); } } }; addNewAttributeAction = new AwsAction(AwsToolkitMetricType.EXPLORER_DYNAMODB_ADD_NEW_ATTRIBUTE) { @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD); } @Override public String getText() { return "Add attribute column"; } @Override protected void doRun() { NewAttributeDialog dialog = new NewAttributeDialog(); if ( dialog.open() == 0 ) { contentProvider.columns.add(dialog.getNewAttributeName()); contentProvider.createColumn(viewer.getTable(), (TableColumnLayout) viewer.getTable().getParent() .getLayout(), dialog.getNewAttributeName()); viewer.getTable().getParent().layout(); actionSucceeded(); } else { actionCanceled(); } actionFinished(); } final class NewAttributeDialog extends AbstractAddNewAttributeDialog { @Override public void validate() { if ( getButton(0) == null ) return; if ( getNewAttributeName().length() == 0 || contentProvider.columns.contains(getNewAttributeName()) ) { getButton(0).setEnabled(false); return; } getButton(0).setEnabled(true); return; } } }; runScanAction.setEnabled(false); saveAction.setEnabled(false); nextPageResultsAction.setEnabled(false); exportAsCSVAction.setEnabled(false); addNewAttributeAction.setEnabled(false); toolBarManager.add(runScanAction); toolBarManager.add(nextPageResultsAction); toolBarManager.add(saveAction); toolBarManager.add(exportAsCSVAction); toolBarManager.add(addNewAttributeAction); toolBarManager.update(true); } private void createResultsTable(Composite resultsComposite) { TableColumnLayout tableColumnLayout = new TableColumnLayout(); resultsComposite.setLayout(tableColumnLayout); this.viewer = new TableViewer(resultsComposite); this.viewer.getTable().setLinesVisible(true); this.viewer.getTable().setHeaderVisible(true); this.contentProvider = new ContentProvider(); this.viewer.setContentProvider(this.contentProvider); this.viewer.setLabelProvider(new LabelProvider()); final Table table = this.viewer.getTable(); final TableEditor editor = new TableEditor(table); editor.horizontalAlignment = SWT.LEFT; editor.grabHorizontal = true; final TextCellEditorListener listener = new TextCellEditorListener(table, editor); table.addListener(SWT.MouseUp, listener); table.addListener(SWT.FocusOut, listener); table.addListener(SWT.KeyDown, listener); MenuManager menuManager = new MenuManager("#PopupMenu"); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { if ( table.getSelectionCount() > 0 ) { manager.add(new Action() { @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE); } @Override public void run() { listener.deleteItems(); } @Override public String getText() { if ( table.getSelectionCount() == 1 ) { return "Delete selected item"; } else { return "Delete selected items"; } } }); } } }); table.setMenu(menuManager.createContextMenu(table)); } @Override public void setFocus() { // no-op } /** * Updates the query results asynchronously. Must be called from the UI * thread. */ private void runScan() { // Clear out the existing table and edit states this.viewer.getTable().setEnabled(false); runScanAction.setEnabled(false); nextPageResultsAction.setEnabled(false); exportAsCSVAction.setEnabled(false); addNewAttributeAction.setEnabled(false); editedItems.clear(); deletedItems.clear(); // this.exportAsCSV.setEnabled(false); for ( TableColumn col : this.viewer.getTable().getColumns() ) { col.dispose(); } new Thread() { @Override public void run() { if ( tableKey == null ) { DescribeTableResult describeTable = AwsToolkitCore .getClientFactory(DynamoDBTableEditor.this.tableEditorInput.getAccountId()) .getDynamoDBV2Client() .describeTable(new DescribeTableRequest().withTableName(tableEditorInput.getTableName())); TableDescription tableDescription = describeTable.getTable(); tableKey = convertToKeySchemaWithAttributeType(tableDescription); } scanResult = new ScanResult(); try { ScanRequest scanRequest = new ScanRequest().withTableName(tableEditorInput.getTableName()); scanRequest.setScanFilter(new HashMap<String, Condition>()); for ( ScanConditionRow row : scanConditions ) { if ( row.shouldExecute() ) { scanRequest.getScanFilter().put(row.getAttributeName(), row.getScanCondition()); } } scanResult = AwsToolkitCore.getClientFactory(DynamoDBTableEditor.this.tableEditorInput.getAccountId()) .getDynamoDBV2Client().scan(scanRequest); } catch ( Exception e ) { DynamoDBPlugin.getDefault().reportException(e.getMessage(), e); return; } final ScanResult result = scanResult; Display.getDefault().asyncExec(new Runnable() { @Override public void run() { viewer.setInput(result.getItems()); viewer.getTable().setEnabled(true); viewer.getTable().getParent().layout(); runScanAction.setEnabled(true); nextPageResultsAction.setEnabled(scanResult.getLastEvaluatedKey() != null); exportAsCSVAction.setEnabled(true); addNewAttributeAction.setEnabled(true); } }); } }.start(); } /** * Fetches the next page of results from the scan and updates the table with them. */ private void getNextPageResults() { this.viewer.getTable().setEnabled(false); runScanAction.setEnabled(false); nextPageResultsAction.setEnabled(false); exportAsCSVAction.setEnabled(false); new Thread() { @Override public void run() { try { ScanRequest scanRequest = new ScanRequest().withTableName(tableEditorInput.getTableName()); scanRequest.setScanFilter(new HashMap<String, Condition>()); for ( ScanConditionRow row : scanConditions ) { if ( row.shouldExecute() ) { scanRequest.getScanFilter().put(row.getAttributeName(), row.getScanCondition()); } } scanRequest.setExclusiveStartKey(scanResult.getLastEvaluatedKey()); scanResult = AwsToolkitCore.getClientFactory(DynamoDBTableEditor.this.tableEditorInput.getAccountId()) .getDynamoDBV2Client().scan(scanRequest); } catch ( Exception e ) { DynamoDBPlugin.getDefault().reportException(e.getMessage(), e); return; } final ScanResult result = scanResult; Display.getDefault().asyncExec(new Runnable() { @Override public void run() { contentProvider.addItems(result.getItems()); viewer.refresh(); DynamoDBTableEditor.this.viewer.getTable().setEnabled(true); DynamoDBTableEditor.this.viewer.getTable().getParent().layout(); runScanAction.setEnabled(true); nextPageResultsAction.setEnabled(scanResult.getLastEvaluatedKey() != null); exportAsCSVAction.setEnabled(true); } }); } }.start(); } /** * Content provider creates columns for the table and keeps track of them * for other parts of the UI. */ private class ContentProvider implements IStructuredContentProvider { private List<Map<String, AttributeValue>> input; private final List<Map<String, AttributeValue>> elementList = new ArrayList<>(); private final List<String> columns = new ArrayList<>(); /** * Adds a single item to the table. */ void addItem(Map<String, AttributeValue> item) { elementList.set(elementList.size() - 1, item); elementList.add(new HashMap<String, AttributeValue>()); viewer.refresh(); } /** * Adds a list of new items to the table. */ public void addItems(List<Map<String, AttributeValue>> items) { // Remove the (possible) empty row and add it to the end if ( !elementList.isEmpty() && elementList.get(elementList.size() - 1).isEmpty() ) { elementList.remove(elementList.size() - 1); } elementList.addAll(items); // expand columns if necessary List<String> columns = new LinkedList<>(); for ( Map<String, AttributeValue> item : items ) { columns.addAll(item.keySet()); } Table table = (Table) viewer.getControl(); TableColumnLayout layout = (TableColumnLayout) table.getParent().getLayout(); for ( String column : columns ) { if ( !this.columns.contains(column) ) { this.columns.add(column); createColumn(table, layout, column); } } // empty row for adding new rows elementList.add(new HashMap<String, AttributeValue>()); } @Override @SuppressWarnings("unchecked") public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { this.input = (List<Map<String, AttributeValue>>) newInput; this.elementList.clear(); this.columns.clear(); initializeElements(); if ( this.input != null ) { Table table = (Table) viewer.getControl(); TableColumnLayout layout = (TableColumnLayout) table.getParent().getLayout(); for ( String col : this.columns ) { createColumn(table, layout, col); } } } private void createColumn(Table table, TableColumnLayout layout, String col) { TableColumn column = new TableColumn(table, SWT.NONE); column.setText(col); layout.setColumnData(column, new ColumnWeightData(10)); } @Override public void dispose() { } @Override public Object[] getElements(final Object inputElement) { initializeElements(); return this.elementList.toArray(); } private synchronized void initializeElements() { if ( elementList.isEmpty() && input != null ) { Set<String> columns = new HashSet<>(); for ( Map<String, AttributeValue> item : input ) { columns.addAll(item.keySet()); } // We add the hash and range keys back in at the beginning, so // remove them for now columns.remove(tableKey.getHashKeyAttributeName()); if ( tableKey.hasRangeKey() ) { columns.remove(tableKey.getRangeKeyAttributeName()); } List<String> sortedColumns = new ArrayList<>(); sortedColumns.addAll(columns); Collections.sort(sortedColumns); sortedColumns.add(0, tableKey.getHashKeyAttributeName()); if ( tableKey.hasRangeKey() ) { sortedColumns.add(1, tableKey.getRangeKeyAttributeName()); } synchronized (knownAttributes) { knownAttributes.addAll(sortedColumns); } elementList.addAll(input); // empty row at the end for adding new rows elementList.add(new HashMap<String, AttributeValue>()); this.columns.addAll(sortedColumns); } } private synchronized List<String> getColumns() { return this.columns; } } private class LabelProvider extends AbstractTableLabelProvider { @Override public String getColumnText(final Object element, final int columnIndex) { @SuppressWarnings("unchecked") Map<String, AttributeValue> item = (Map<String, AttributeValue>) element; String column = DynamoDBTableEditor.this.contentProvider.getColumns().get(columnIndex); AttributeValue values = item.get(column); return format(values); } } /** * CreateNewItemDialog now extends AttributeValueInputDialog, which is a * more generic class that includes basic dialog template and value * validation. */ private final class CreateNewItemDialog extends AttributeValueInputDialog { @SuppressWarnings("serial") private CreateNewItemDialog() { super("Create new item", "Enter the key for the new item", true, new ArrayList<String>() {{ add(tableKey.getHashKeyAttributeName()); if (tableKey.getRangeKeyAttributeName() != null) { add(tableKey.getRangeKeyAttributeName()); } }}, new HashMap<String, Integer>() {{ put(tableKey.getHashKeyAttributeName(), getDataType(tableKey.getHashKeyAttributeType())); if (tableKey.getRangeKeyAttributeName() != null) { put(tableKey.getRangeKeyAttributeName(), getDataType(tableKey.getRangeKeyAttributeType())); } }}, null); } Map<String, AttributeValue> getNewItem() { String hashKey = attributeValues.get(tableKey.getHashKeyAttributeName()); String rangeKey = attributeValues.get(tableKey.getRangeKeyAttributeName()); Map<String, AttributeValue> item = new HashMap<>(); AttributeValue hashKeyAttribute = new AttributeValue(); setAttribute(hashKeyAttribute, Arrays.asList(hashKey), tableKey.getHashKeyAttributeType()); item.put(tableKey.getHashKeyAttributeName(), hashKeyAttribute); if ( rangeKey != null && rangeKey.length() > 0 ) { AttributeValue rangeKeyAttribute = new AttributeValue(); setAttribute(rangeKeyAttribute, Arrays.asList(rangeKey), tableKey.getRangeKeyAttributeType()); item.put(tableKey.getRangeKeyAttributeName(), rangeKeyAttribute); } return item; } } /** * Listener to respond to clicks in a cell, invoking a cell editor */ private final class TextCellEditorListener implements Listener { private final Table table; private final TableEditor editor; private AttributeValueEditor editorComposite; private TextCellEditorListener(final Table table, final TableEditor editor) { this.table = table; this.editor = editor; } @Override public void handleEvent(final Event event) { if ( event.type == SWT.FocusOut && this.editorComposite != null && !this.editorComposite.isDisposed() ) { Control focus = Display.getCurrent().getFocusControl(); if ( focus != this.editorComposite && focus != this.editorComposite.editorText && focus != this.table ) { this.editorComposite.dispose(); } } else if (event.type == SWT.KeyDown && event.keyCode == SWT.DEL) { deleteItems(); return; } else if (event.type != SWT.MouseUp || event.button != 1) { return; } Rectangle clientArea = this.table.getClientArea(); Point pt = new Point(event.x, event.y); int row = table.getTopIndex(); while ( row < table.getItemCount() ) { boolean visible = false; final TableItem item = this.table.getItem(row); // We don't care about clicks in the first 1 or 2 columns since // they are read-only, except in the last row. final boolean isLastRow = row == table.getItemCount() - 1; int numKeyColumns = tableKey.hasRangeKey() ? 2 : 1; for ( int col = 0; col < table.getColumnCount(); col++ ) { Rectangle rect = item.getBounds(col); if ( rect.contains(pt) ) { if ( editorComposite != null && !editorComposite.isDisposed() ) { editorComposite.dispose(); } if ( isLastRow ) { invokeNewItemDialog(item, row); return; } else if ( col < numKeyColumns ) { // table.select(row); return; } final int column = col; final int rowNum = row; final String attributeName = item.getParent().getColumn(col).getText(); @SuppressWarnings("unchecked") Map<String, AttributeValue> dynamoDbItem = (Map<String, AttributeValue>) item.getData(); final AttributeValue attributeValue = dynamoDbItem.containsKey(attributeName) ? dynamoDbItem .get(attributeName) : new AttributeValue(); // If this is a binary value, don't allow editing if ( attributeValue != null && (attributeValue.getBS() != null || attributeValue.getB() != null) ) { invokeBinaryValueDialog(item, attributeName, column, rowNum); return; } // Don't support editing new data types if ( attributeValue != null && (attributeValue.getBOOL() != null || attributeValue.getNULL() != null || attributeValue.getM() != null || attributeValue.getL() != null) ) { Dialog dialog = new MessageDialog( Display.getDefault().getActiveShell(), "Attribute edit not supported", AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON), "Editing BOOL/NULL/Map/List attributes is currently not supported.", MessageDialog.NONE, new String[] { "OK" }, 0); dialog.open(); return; } configureCellEditor(item, column, rowNum, attributeName, attributeValue); // If this is a multi-value item, don't allow textual editing if ( attributeValue != null && (attributeValue.getSS() != null || attributeValue.getNS() != null || attributeValue.getBS() != null) ) { editorComposite.editorText.setEditable(false); editorComposite.editorText.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { invokeMultiValueDialog(item, attributeName, column, rowNum, editorComposite.dataTypeCombo.getSelectionIndex()); editorComposite.dispose(); } }); return; } editorComposite.editorText.selectAll(); editorComposite.editorText.setFocus(); return; } if ( !visible && rect.intersects(clientArea) ) { visible = true; } } if ( !visible ) { return; } row++; } } /** * Invokes a dialog showing a binary value or set of values. */ private void invokeBinaryValueDialog(TableItem item, String attributeName, int column, int rowNum) { Dialog dialog = new MessageDialog( Display.getDefault().getActiveShell(), "Binary attribute", AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON), "This is a binary attribute. Editing binary attributes is unsupported, " + "but you can copy the base64 encoding of this attribute to the clipboard.", MessageDialog.NONE, new String[] { "Copy to clipboard", "Cancel" }, 0); int result = dialog.open(); if ( result == 0 ) { Clipboard cb = new Clipboard(Display.getDefault()); String data = item.getText(column); TextTransfer textTransfer = TextTransfer.getInstance(); cb.setContents(new Object[] { data }, new Transfer[] { textTransfer }); } } /** * Deletes all selected items from the table. */ private void deleteItems() { List<Integer> selectionIndices = new ArrayList<>(); for (int i : table.getSelectionIndices()) { selectionIndices.add(i); } // Remove all these indices from the data model of the content // provider. We go through them backwards to avoid having to // recalculate offsets caused by the list shifting to fill in the // gaps. Collections.sort(selectionIndices); for (int i = selectionIndices.size() - 1; i >= 0; i--) { Integer selectionIndex = selectionIndices.get(i); contentProvider.elementList.remove(selectionIndex.intValue()); Map<String, AttributeValue> key = getKey(table.getItem(selectionIndex)); editedItems.remove(key); // If this is a newly-added item, don't try to issue a delete // request for it. if ( addedItems.contains(key) ) { addedItems.remove(key); } else { deletedItems.add(key); } } markDirty(); viewer.refresh(); } /** * Configures the member cell editor for the table item and column * given. */ private void configureCellEditor(final TableItem item, final int column, final int rowNum, final String attributeName, final AttributeValue attributeValue) { this.editorComposite = new AttributeValueEditor(this.table, SWT.None, editor, table.getItemHeight(), attributeValue); editor.setEditor(this.editorComposite, item, column); editorComposite.editorText.setText(item.getText(column)); editorComposite.editorText.addModifyListener(new ModifyListener() { @Override public void modifyText(final ModifyEvent e) { Text text = editorComposite.editorText; int dataType = editorComposite.getSelectedDataType(false); markModified(item, text, rowNum, column, Arrays.asList(text.getText()), dataType); } }); /* * We validate the user input of the scalar value when the text * editor is being disposed. (For set type, the validation happens in MultiValueAttributeEditorDialog.) */ editorComposite.editorText.addDisposeListener(new DisposeListener() { @Override @SuppressWarnings({ "serial", "unchecked" }) public void widgetDisposed(DisposeEvent e) { AttributeValue updateAttributeValue = ( (Map<String, AttributeValue>)item.getData() ).get(attributeName); boolean isScalarAttribute = updateAttributeValue != null && ( updateAttributeValue.getN() != null || updateAttributeValue.getS() != null || updateAttributeValue.getB() != null); /* Only do validation when it is a scalar type. */ if ( isScalarAttribute ) { final String attributeInput = editorComposite.editorText.getText(); final int dataType = editorComposite.getSelectedDataType(false); if ( !AttributeValueUtil.validateScalarAttributeInput(attributeInput, dataType, false) ) { /* Open up a non-cancelable input dialog */ AttributeValueInputDialog attributeValueInputDialog = new AttributeValueInputDialog( "Invalid attribute value", "Please provide a valid value for the following attribute", false, Arrays.asList(attributeName), new HashMap<String, Integer>() {{ put(attributeName, dataType); }}, new HashMap<String, String>() {{ put(attributeName, attributeInput); }}); attributeValueInputDialog.open(); /* Update the attribute editor and markModified */ Text text = editorComposite.editorText; String validatedValue = attributeValueInputDialog.getInputValue(attributeName); text.setText(validatedValue); markModified(item, text, rowNum, column, Arrays.asList(text.getText()), dataType); } } } }); editorComposite.editorText.addTraverseListener(new TraverseListener() { @Override public void keyTraversed(final TraverseEvent e) { TextCellEditorListener.this.editorComposite.dispose(); } }); editorComposite.multiValueEditorButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { invokeMultiValueDialog(item, attributeName, column, rowNum, editorComposite.dataTypeCombo.getSelectionIndex()); editorComposite.dispose(); } }); // Changing the data type must be marked as a change editorComposite.dataTypeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Collection<String> values = getValuesFromAttribute(attributeValue); int dataType; switch (editorComposite.dataTypeCombo.getSelectionIndex()) { case STRING: if ( attributeValue.getS() != null || attributeValue.getSS() != null ) return; if ( values.size() > 1 ) { dataType = SS; } else { dataType = S; } break; case NUMBER: if ( attributeValue.getN() != null || attributeValue.getNS() != null ) return; if ( values.size() > 1 ) { dataType = NS; } else { dataType = N; } break; default: throw new RuntimeException("Unexpected selection index " + editorComposite.dataTypeCombo.getSelectionIndex()); } markModified(item, editorComposite.editorText, rowNum, column, values, dataType); } }); } private void invokeMultiValueDialog(final TableItem item, final String attributeName, final int column, final int row, final int selectedType) { @SuppressWarnings("unchecked") Map<String, AttributeValue> dynamoDbItem = (Map<String, AttributeValue>) item.getData(); MultiValueAttributeEditorDialog multiValueEditorDialog = new MultiValueAttributeEditorDialog(Display .getDefault().getActiveShell(), dynamoDbItem.get(attributeName), selectedType); int returnValue = multiValueEditorDialog.open(); /* Save set */ if ( returnValue == 0 ) { int dataType = editorComposite.getSelectedDataType(true); markModified(item, editorComposite.editorText, row, column, multiValueEditorDialog.getValues(), dataType); } /* Save single value */ else if ( returnValue == 1 ) { int dataType = editorComposite.getSelectedDataType(false); markModified(item, editorComposite.editorText, row, column, multiValueEditorDialog.getValues(), dataType); } /* Don't do anything when the user pressed Cancel */ } } /** * Invokes a new dialog to allow creation of a new item in the table. */ private void invokeNewItemDialog(TableItem tableItem, int row) { CreateNewItemDialog dialog = new CreateNewItemDialog(); int result = dialog.open(); if ( result == 0 ) { Map<String, AttributeValue> newItem = dialog.getNewItem(); contentProvider.addItem(newItem); Map<String, AttributeValue> key = getKey(tableItem); addedItems.add(key); markModified(tableItem, null, row, 0, getValuesFromAttribute(newItem.get(tableKey.getHashKeyAttributeName())), getDataType(tableKey.getHashKeyAttributeType())); if ( tableKey.hasRangeKey() ) { markModified(tableItem, null, row, 1, getValuesFromAttribute(newItem.get(tableKey.getRangeKeyAttributeName())), getDataType(tableKey.getRangeKeyAttributeType())); } } } /** * Marks the given tree item and column modified. * * TODO: type checking for numbers */ protected void markModified(final TableItem item, final Text editorControl, final int row, final int column, final Collection<String> newValue, int dataType) { final String attributeName = item.getParent().getColumn(column).getText(); @SuppressWarnings("unchecked") Map<String, AttributeValue> dynamoDbItem = (Map<String, AttributeValue>) item.getData(); AttributeValue attributeValue = dynamoDbItem.get(attributeName); if ( attributeValue == null ) { attributeValue = new AttributeValue(); dynamoDbItem.put(attributeName, attributeValue); } setAttribute(attributeValue, newValue, dataType); Map<String, AttributeValue> editedItemKey = getKey(item); if ( !editedItems.containsKey(editedItemKey) ) { editedItems.add(editedItemKey, new EditedItem(dynamoDbItem, item)); } // Don't add key attributes to the list of edited attributes if ( !attributeName.equals(tableKey.getHashKeyAttributeName()) && ( !tableKey.hasRangeKey() || !attributeName.equals(tableKey.getRangeKeyAttributeName())) ) { editedItems.get(editedItemKey).markAttributeEdited(attributeName); } // We may already have another entry here, but since we're updating the // data model as we go, we can overwrite as many times as we want. editedItems.update(editedItemKey, dynamoDbItem); item.setText(column, format(attributeValue)); // Treat the empty string as a null for easier saving if ( newValue.size() == 1 && newValue.iterator().next().length() == 0 ) { dynamoDbItem.remove(attributeName); } item.setForeground(column, Display.getDefault().getSystemColor(SWT.COLOR_RED)); if ( editorControl != null ) editorControl.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_RED)); markDirty(); } /** * Returns a key for recording a change to the item given, reusing the key * if it exists or returning a new one otherwise. */ private Map<String, AttributeValue> getKey(final TableItem item) { @SuppressWarnings("unchecked") Map<String, AttributeValue> dynamoDbItem = (Map<String, AttributeValue>) item.getData(); Map<String, AttributeValue> keyAttributes = new HashMap<>(); String hashKeyAttributeName = tableKey.getHashKeyAttributeName(); keyAttributes.put(hashKeyAttributeName, dynamoDbItem.get(hashKeyAttributeName)); if ( tableKey.hasRangeKey() ) { String rangeKeyAttributeName = tableKey.getRangeKeyAttributeName(); keyAttributes.put(rangeKeyAttributeName, dynamoDbItem.get(rangeKeyAttributeName)); } return keyAttributes; } /** * Use DynamoDB V2 to get the attribtue names and types of both hash and range keys * of the table, and then save them in a KeySchemaWithAttributeType object. */ private static KeySchemaWithAttributeType convertToKeySchemaWithAttributeType( TableDescription table) { KeySchemaWithAttributeType keySchema = new KeySchemaWithAttributeType(); String hashKeyAttributeName = null; String rangeKeyAttributeName = null; for (KeySchemaElement key : table.getKeySchema()) { if (key.getKeyType().equals(KeyType.HASH.toString())) { hashKeyAttributeName = key.getAttributeName(); } else if (key.getKeyType().equals(KeyType.RANGE.toString())) { rangeKeyAttributeName = key.getAttributeName(); } } for (AttributeDefinition attribute : table.getAttributeDefinitions()) { if (hashKeyAttributeName.equals(attribute.getAttributeName())) { keySchema.setHashKeyElement(hashKeyAttributeName, attribute.getAttributeType()); } if (rangeKeyAttributeName != null && rangeKeyAttributeName.equals(attribute .getAttributeName())) { keySchema.setRangeKeyElement(rangeKeyAttributeName, attribute.getAttributeType()); } } return keySchema; } /** * DynamoDB v2 no longer returns AttributeType as part of KeySchemaElement, * so we use this class to record the attribute names and types of both * hash key and range key. * */ private static class KeySchemaWithAttributeType { private String hashKeyAttributeName; private String hashKeyAttributeType; private String rangeKeyAttributeName; private String rangeKeyAttributeType; public void setHashKeyElement(String attributeName, String attributeType) { hashKeyAttributeName = attributeName; hashKeyAttributeType = attributeType; } public void setRangeKeyElement(String attributeName, String attributeType) { rangeKeyAttributeName = attributeName; rangeKeyAttributeType = attributeType; } public boolean hasRangeKey() { return rangeKeyAttributeName != null && rangeKeyAttributeType != null; } public String getHashKeyAttributeName() { return hashKeyAttributeName; } public String getHashKeyAttributeType() { return hashKeyAttributeType; } public String getRangeKeyAttributeName() { return rangeKeyAttributeName; } public String getRangeKeyAttributeType() { return rangeKeyAttributeType; } } }
7,153
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/MultiValueAttributeEditorDialog.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.dynamodb.editor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueEditor.STRING; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueEditor.NUMBER; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.S; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.N; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.ui.MultiValueEditorDialog; import com.amazonaws.services.dynamodbv2.model.AttributeValue; /** * Simple table dialog to allow user to enter multiple values for an * attribute. */ class MultiValueAttributeEditorDialog extends MultiValueEditorDialog { private int scalarDataType; public MultiValueAttributeEditorDialog(final Shell parentShell, final AttributeValue attributeValue, int selectedType) { super(parentShell, "Edit values", AwsToolkitCore.getDefault().getImageRegistry() .get(AwsToolkitCore.IMAGE_AWS_ICON), "", MessageDialog.NONE, new String[] { "Save set", "Save single value", "Cancel"}, 0); this.values.addAll(AttributeValueUtil.getValuesFromAttribute(attributeValue)); String dataTypeDescription; switch (selectedType) { case STRING: dataTypeDescription = "(String set)"; scalarDataType = S; break; case NUMBER: dataTypeDescription = "(Number set)"; scalarDataType = N; break; default: dataTypeDescription = ""; break; } addColumnTextDescription(dataTypeDescription); } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); this.getButton(1).setEnabled(values.size() == 1); } @Override protected void modifyValue(TableItem item, int column, int index, Text text) { super.modifyValue(item, column, index, text); this.getButton(1).setEnabled(values.size() == 1); this.getButtonBar().update(); } @Override protected void lockTableEditor(int index) { /* Also lock the Save single value button */ this.getButton(1).setEnabled(false); super.lockTableEditor(index); } @Override protected void unlockTableEditor() { /* Also unlock the Save single value button */ this.getButton(1).setEnabled(values.size() == 1); super.unlockTableEditor(); } @Override protected boolean validateAttributeValue(String attributeValue) { return AttributeValueUtil.validateScalarAttributeInput(attributeValue, scalarDataType, true); } }
7,154
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/OpenTableEditorAction.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.dynamodb.editor; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; /** * Opens up the custom query editor on a given domain */ public class OpenTableEditorAction extends AwsAction { private final String tableName; public OpenTableEditorAction(final String domainName) { super(AwsToolkitMetricType.EXPLORER_DYNAMODB_OPEN_TABLE_EDITOR); this.tableName = domainName; setText("Open Query Editor"); setToolTipText("Opens the query editor to run queries against this domain"); } @Override protected void doRun() { try { IWorkbenchPage workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); workbenchPage.openEditor(new TableEditorInput(this.tableName, AwsToolkitCore.getDefault() .getCurrentAccountId()), DynamoDBTableEditor.ID); actionSucceeded(); } catch ( PartInitException e ) { actionFailed(); AwsToolkitCore.getDefault().logError(e.getMessage(), e); } finally { actionFinished(); } } }
7,155
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/ScanConditionRow.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.dynamodb.editor; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueEditor.*; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.eclipse.jface.fieldassist.ContentProposal; import org.eclipse.jface.fieldassist.IContentProposal; import org.eclipse.jface.fieldassist.IContentProposalProvider; import org.eclipse.jface.fieldassist.TextContentAdapter; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; /** * One row in the scan conditions editor. */ final class ScanConditionRow extends Composite { private static final ComparisonOperator[] COMPARISON_OPERATORS = new ComparisonOperator[] { ComparisonOperator.EQ, ComparisonOperator.NE, ComparisonOperator.GT, ComparisonOperator.GE, ComparisonOperator.LT, ComparisonOperator.LE, ComparisonOperator.BETWEEN, ComparisonOperator.BEGINS_WITH, ComparisonOperator.IN, ComparisonOperator.CONTAINS, ComparisonOperator.NOT_CONTAINS, ComparisonOperator.NULL, ComparisonOperator.NOT_NULL, }; private static final String[] COMPARISON_OPERATOR_STRINGS = new String[] { "Equals", "Not equals", "Greater than", "Greater than or equals", "Less than", "Less than or equals", "Between", "Begins with", "In", "Contains", "Does not contain", "Is null", "Is not null", }; private static final int EQ = 0; private String attributeName; private AttributeValue comparisonValue = new AttributeValue(); private int dataType = S; private ComparisonOperator comparisonOperator = ComparisonOperator.EQ; private final List<Control> conditionallyShownControls = new ArrayList<>(); private boolean enabled = true; private boolean valid = false; /* * Shared with the parent editor object, so must be carefully synchronized. */ private final Collection<String> knownAttributes; /** * Meaningful fields we have to track for fancy UI swapping. */ private Text singleValueEditor; private Text listValueEditor; private Button multiValueEditorButton; private Text betweenTextOne; private Label betweenTextLabel; private Text betweenTextTwo; private Button dataTypeButton; private Combo dataTypeCombo; /** * Returns the attribute name for the scan condition. */ public String getAttributeName() { return attributeName; } /** * Returns the scan condition represented by this row. */ public Condition getScanCondition() { Condition condition = new Condition().withComparisonOperator(comparisonOperator); switch (dataType) { case S: // fall through case SS: if ( comparisonOperator.equals(ComparisonOperator.BETWEEN) ) { // should only be two here condition.withAttributeValueList(new AttributeValue().withS(comparisonValue.getSS().get(0)), new AttributeValue().withS(comparisonValue.getSS().get(1))); } else if ( comparisonOperator.equals(ComparisonOperator.IN) ) { List<AttributeValue> attributeValues = new LinkedList<>(); for ( String value : comparisonValue.getSS() ) { attributeValues.add(new AttributeValue().withS(value)); } condition.withAttributeValueList(attributeValues); } else if ( comparisonOperator.equals(ComparisonOperator.NULL) || comparisonOperator.equals(ComparisonOperator.NOT_NULL) ) { // empty attribute value list } else { condition.withAttributeValueList(comparisonValue); } break; case N: // fall through case NS: if ( comparisonOperator.equals(ComparisonOperator.BETWEEN) ) { // should only be two here condition.withAttributeValueList(new AttributeValue().withN(comparisonValue.getNS().get(0)), new AttributeValue().withN(comparisonValue.getNS().get(1))); } else if ( comparisonOperator.equals(ComparisonOperator.IN) ) { List<AttributeValue> attributeValues = new LinkedList<>(); for ( String value : comparisonValue.getNS() ) { attributeValues.add(new AttributeValue().withN(value)); } condition.withAttributeValueList(attributeValues); } else if ( comparisonOperator.equals(ComparisonOperator.NULL) || comparisonOperator.equals(ComparisonOperator.NOT_NULL) ) { // empty attribute value list } else { condition.withAttributeValueList(comparisonValue); } break; default: throw new RuntimeException("Unrecognized data type " + dataType); } return condition; } public ScanConditionRow(final Composite parent, final Collection<String> knownAttributes) { super(parent, SWT.NONE); this.knownAttributes = knownAttributes; GridLayoutFactory.fillDefaults().numColumns(10).margins(5, 0).applyTo(this); GridDataFactory.fillDefaults().grab(true, false).applyTo(this); // Red X to remove control final Button removeCondition = new Button(this, SWT.PUSH); removeCondition.setToolTipText("Remove condition"); removeCondition.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_REMOVE)); removeCondition.setText(""); removeCondition.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { parent.setRedraw(false); dispose(); parent.layout(true); parent.setRedraw(true); } }); // Check box for enablement of condition final Button enabledButton = new Button(this, SWT.CHECK); enabledButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { enabled = enabledButton.getSelection(); Control[] children = getChildren(); // Skip the first two controls, which are the remove button and // the enable checkbox. for ( int i = 2; i < children.length; i++ ) { children[i].setEnabled(enabled); } validate(); } }); enabledButton.setSelection(true); // Attribute name field final Label attributeNameLabel = new Label(this, SWT.None); attributeNameLabel.setText("Attribute:"); final Text attributeNameText = new Text(this, SWT.BORDER); attributeNameText.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create()); attributeNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { attributeName = attributeNameText.getText(); validate(); } }); setupAttributeNameContentAssist(attributeNameText); GridDataFactory.fillDefaults().grab(true, false).applyTo(attributeNameText); // Comparison selection combo final Combo comparison = new Combo(this, SWT.READ_ONLY | SWT.DROP_DOWN); comparison.setItems(COMPARISON_OPERATOR_STRINGS); comparison.select(EQ); comparison.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { comparisonOperator = COMPARISON_OPERATORS[comparison.getSelectionIndex()]; configureComparisonEditorFields(); validate(); } }); singleValueEditor = new Text(this, SWT.BORDER); singleValueEditor.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { setAttribute(comparisonValue, Arrays.asList(singleValueEditor.getText()), dataTypeCombo.getSelectionIndex() == STRING ? S : N); } }); GridDataFactory.fillDefaults().grab(true, false).applyTo(singleValueEditor); conditionallyShownControls.add(singleValueEditor); listValueEditor = new Text(this, SWT.BORDER); listValueEditor.setEditable(false); listValueEditor.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { invokeMultiValueEditorDialog(); } }); GridDataFactory.fillDefaults().grab(true, false).applyTo(listValueEditor); conditionallyShownControls.add(listValueEditor); multiValueEditorButton = new Button(this, SWT.None); multiValueEditorButton.setText("..."); multiValueEditorButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { invokeMultiValueEditorDialog(); } }); GridDataFactory.swtDefaults().applyTo(multiValueEditorButton); conditionallyShownControls.add(multiValueEditorButton); betweenTextOne = new Text(this, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(betweenTextOne); ModifyListener betweenModifyListener = new ModifyListener() { @Override public void modifyText(ModifyEvent e) { setAttribute(comparisonValue, Arrays.asList(betweenTextOne.getText(), betweenTextTwo.getText()), dataTypeCombo.getSelectionIndex() == STRING ? SS : NS); } }; betweenTextOne.addModifyListener(betweenModifyListener); conditionallyShownControls.add(betweenTextOne); betweenTextLabel = new Label(this, SWT.READ_ONLY); betweenTextLabel.setText(" and "); GridDataFactory.swtDefaults().applyTo(betweenTextLabel); conditionallyShownControls.add(betweenTextLabel); betweenTextTwo = new Text(this, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(betweenTextTwo); betweenTextTwo.addModifyListener(betweenModifyListener); conditionallyShownControls.add(betweenTextTwo); dataTypeButton = new Button(this, SWT.None); dataTypeButton.setImage(DynamoDBPlugin.getDefault().getImageRegistry().get(DynamoDBPlugin.IMAGE_A)); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.TOP).grab(false, true).applyTo(dataTypeButton); dataTypeCombo = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY); dataTypeCombo.setItems(DATA_TYPE_ITEMS); dataTypeCombo.select(STRING); dataTypeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Collection<String> values = getValuesFromAttribute(comparisonValue); switch (dataTypeCombo.getSelectionIndex()) { case STRING: if ( values.size() > 1 ) { dataType = SS; } else { dataType = S; } break; case NUMBER: if ( values.size() > 1 ) { dataType = NS; } else { dataType = N; } break; default: throw new RuntimeException("Unexpected selection index " + dataTypeCombo.getSelectionIndex()); } setAttribute(comparisonValue, values, dataType); } }); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.TOP).grab(false, true).exclude(true).applyTo(dataTypeCombo); dataTypeCombo.setVisible(false); configureDataTypeControlSwap(dataTypeButton, dataTypeCombo, this); conditionallyShownControls.add(dataTypeButton); configureComparisonEditorFields(); } private void invokeMultiValueEditorDialog() { MultiValueAttributeEditorDialog multiValueEditorDialog = new MultiValueAttributeEditorDialog(Display .getDefault().getActiveShell(), comparisonValue, dataTypeCombo.getSelectionIndex()); int returnValue = multiValueEditorDialog.open(); if ( returnValue == 0 || returnValue == 1) { // Save set or single setAttribute(comparisonValue, multiValueEditorDialog.getValues(), dataTypeCombo.getSelectionIndex() == STRING ? SS : NS); listValueEditor.setText(format(comparisonValue)); } } /** * Configures the editor row based on the current comparison, hiding and * showing editor elements as necessary. */ private void configureComparisonEditorFields() { clearAttributes(comparisonValue); setRedraw(false); betweenTextOne.setText(""); betweenTextTwo.setText(""); listValueEditor.setText(""); singleValueEditor.setText(""); List<Control> toHide = new LinkedList<>(); toHide.addAll(conditionallyShownControls); toHide.add(dataTypeCombo); for ( Control c : toHide ) { c.setVisible(false); GridDataFactory.createFrom((GridData) c.getLayoutData()).exclude(true).applyTo(c); } Collection<Control> toShow = new LinkedList<>(); switch (comparisonOperator) { case BEGINS_WITH: toShow.add(singleValueEditor); dataType = S; break; case BETWEEN: toShow.add(betweenTextOne); toShow.add(betweenTextLabel); toShow.add(betweenTextTwo); toShow.add(dataTypeButton); switch (dataType) { case N: case NS: dataType = N; break; case S: case SS: dataType = S; break; } break; case IN: toShow.add(dataTypeButton); toShow.add(multiValueEditorButton); toShow.add(listValueEditor); switch (dataType) { case N: case NS: dataType = NS; break; case S: case SS: dataType = SS; break; } break; case EQ: case GE: case GT: case LE: case LT: case NE: case CONTAINS: case NOT_CONTAINS: toShow.add(dataTypeButton); toShow.add(singleValueEditor); switch (dataType) { case N: case NS: dataType = N; break; case S: case SS: dataType = S; break; } break; case NOT_NULL: case NULL: break; default: throw new RuntimeException("Unknown comparison " + comparisonOperator); } for ( Control c : toShow ) { c.setVisible(true); GridDataFactory.createFrom((GridData) c.getLayoutData()).exclude(false).applyTo(c); } layout(); setRedraw(true); } /** * Returns whether this scan condition should be included in the scan * request sent to DynamoDB */ public boolean shouldExecute() { return enabled && valid; } private void validate() { valid = true; } /** * Sets up content assist on the Text control given with the list of valid * completions for it. Returns the ContestAssist object. */ private ContentAssistCommandAdapter setupAttributeNameContentAssist(final Text text) { // Our simplified proposer doesn't quite work with a vanilla content // adapter implementation, so we have to tweak it a bit to get the // desired behavior. TextContentAdapter controlContentAdapter = new TextContentAdapter() { @Override public void insertControlContents(Control control, String value, int cursorPosition) { text.setText(value); } }; ContentAssistCommandAdapter assist = new ContentAssistCommandAdapter(text, controlContentAdapter, new StringContentProposalProvider(), null, null, true); // the assist adapter turns off auto-complete for normal typing, so turn // it back on assist.setAutoActivationCharacters(null); assist.setAutoActivationDelay(100); return assist; } /** * An IContentProposalProvider that deals in a set of strings */ final class StringContentProposalProvider implements IContentProposalProvider { @Override public IContentProposal[] getProposals(String contents, int position) { synchronized (knownAttributes) { List<ContentProposal> list = new ArrayList<>(); String target = contents.trim().toLowerCase(); for ( String name : knownAttributes ) { if ( name.toLowerCase().startsWith(target) ) { list.add(new ContentProposal(name)); } } return list.toArray(new IContentProposal[list.size()]); } } } }
7,156
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/EditedItems.java
/* * Copyright 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.dynamodb.editor; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.dynamodbv2.model.AttributeValue; /** * Collection type for edited items in the dynamo table editor. */ public class EditedItems { /* * Linked hash map preserves order of insertion so that iterations are made * in the same order as insertions. This is so that updates are done in the * same order as edits. */ private final Map<Map<String, AttributeValue>, EditedItem> editedItems = new LinkedHashMap<>(); /** * @see java.util.Map#get(java.lang.Object) */ public EditedItem get(Map<String, AttributeValue> key) { return editedItems.get(key); } /** * @see java.util.Map#put(java.lang.Object, java.lang.Object) */ public void add(Map<String, AttributeValue> key, EditedItem value) { editedItems.put(key, value); } /** * Updates the item with the key given to contain the attributes given. */ public void update(Map<String, AttributeValue> key, Map<String, AttributeValue> dynamoItem) { editedItems.get(key).setAttributes(dynamoItem); } /** * @see java.util.Map#containsKey(java.lang.Object) */ public boolean containsKey(Object key) { return editedItems.containsKey(key); } /** * @see java.util.Map#remove(java.lang.Object) */ public EditedItem remove(Map<String, AttributeValue> key) { return editedItems.remove(key); } /** * @see java.util.Map#clear() */ public void clear() { editedItems.clear(); } /** * Returns an iterator over all the entries in the collection. */ public Iterator<Entry<Map<String, AttributeValue>, EditedItem>> iterator() { return editedItems.entrySet().iterator(); } /** * @see java.util.Map#isEmpty() */ public boolean isEmpty() { return editedItems.isEmpty(); } /** * @see java.util.Map#size() */ public int size() { return editedItems.size(); } }
7,157
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/AttributeValueEditor.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.dynamodb.editor; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.N; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.S; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.NS; import static com.amazonaws.eclipse.dynamodb.editor.AttributeValueUtil.SS; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ControlEditor; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; 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.Display; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.services.dynamodbv2.model.AttributeValue; /** * Editor for attribute values including multi-value pop-up and data type * selection. */ final class AttributeValueEditor extends Composite { /* * Data types for the drop-down box. */ static final String[] DATA_TYPE_ITEMS = new String[] { "String", "Number" }; static final int STRING = 0; static final int NUMBER = 1; Text editorText; Button multiValueEditorButton; Button dataTypeButton; Combo dataTypeCombo; public AttributeValueEditor(Composite parent, int style, ControlEditor editor, int controlHeight, AttributeValue attributeValue) { super(parent, style); this.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); GridLayout layout = new GridLayout(3, false); layout.marginHeight = 0; layout.marginWidth = 2; layout.verticalSpacing = 0; layout.horizontalSpacing = 0; this.setLayout(layout); // Text field for typing in new values editorText = new Text(this, SWT.NONE); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, false).indent(2, 2).applyTo(editorText); // Button for invoking a multi-value editor multiValueEditorButton = new Button(this, SWT.None); multiValueEditorButton.setText("..."); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.TOP).grab(false, true).applyTo(this.multiValueEditorButton); multiValueEditorButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); // Button for changing data type dataTypeButton = new Button(this, SWT.None); int selectedType; if ( attributeValue.getN() != null || attributeValue.getNS() != null ) { dataTypeButton.setImage(DynamoDBPlugin.getDefault().getImageRegistry().get(DynamoDBPlugin.IMAGE_ONE)); selectedType = NUMBER; } else { // Default image and selected type is STRING dataTypeButton.setImage(DynamoDBPlugin.getDefault().getImageRegistry().get(DynamoDBPlugin.IMAGE_A)); selectedType = STRING; } GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.TOP).grab(false, true).applyTo(this.dataTypeButton); dataTypeButton.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); // Combo for selecting a data type once the above button is clicked. dataTypeCombo = new Combo(this, SWT.READ_ONLY | SWT.DROP_DOWN); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.TOP).grab(false, true).exclude(true) .applyTo(this.dataTypeCombo); dataTypeCombo.setVisible(false); dataTypeCombo.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); dataTypeCombo.setItems(DATA_TYPE_ITEMS); dataTypeCombo.select(selectedType); if ( editor != null ) { Point comboSize = dataTypeCombo.computeSize(SWT.DEFAULT, controlHeight); editor.minimumWidth = comboSize.x; editor.minimumHeight = comboSize.y; } configureDataTypeControlSwap(dataTypeButton, dataTypeCombo, this); } /** * Swaps the display of the two controls given when either is selected. */ static void configureDataTypeControlSwap(final Button dataTypeButton, final Combo dataTypeCombo, final Composite parent) { dataTypeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { parent.setRedraw(false); dataTypeButton.setVisible(false); GridDataFactory.createFrom((GridData) dataTypeButton.getLayoutData()).exclude(true) .applyTo(dataTypeButton); dataTypeCombo.setVisible(true); GridDataFactory.createFrom((GridData) dataTypeCombo.getLayoutData()).exclude(false) .applyTo(dataTypeCombo); parent.layout(); dataTypeCombo.setListVisible(true); parent.setRedraw(true); } }); dataTypeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { parent.setRedraw(false); dataTypeCombo.setVisible(false); GridDataFactory.createFrom((GridData) dataTypeCombo.getLayoutData()).exclude(true) .applyTo(dataTypeCombo); dataTypeButton.setVisible(true); GridDataFactory.createFrom((GridData) dataTypeButton.getLayoutData()).exclude(false) .applyTo(dataTypeButton); if ( dataTypeCombo.getSelectionIndex() == STRING ) { dataTypeButton.setImage(DynamoDBPlugin.getDefault().getImageRegistry().get(DynamoDBPlugin.IMAGE_A)); } else { dataTypeButton.setImage(DynamoDBPlugin.getDefault().getImageRegistry().get(DynamoDBPlugin.IMAGE_ONE)); } parent.layout(); parent.setRedraw(true); } }); } /** * Returns the currently selected data type. */ public int getSelectedDataType(boolean isSetType) { int dataType; switch (this.dataTypeCombo.getSelectionIndex()) { case STRING: dataType = isSetType ? SS : S; break; case NUMBER: dataType = isSetType ? NS : N; break; default: throw new RuntimeException("Unexpected selection index " + this.dataTypeCombo.getSelectionIndex()); } return dataType; } }
7,158
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/TableEditorInput.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.dynamodb.editor; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPersistableElement; import com.amazonaws.eclipse.core.AwsToolkitCore; /** * Editor input for the custom query editor */ public class TableEditorInput implements IEditorInput { private final String tableName; private final String accountId; String getAccountId() { return this.accountId; } public TableEditorInput(final String domainName, final String accountId) { super(); this.tableName = domainName; this.accountId = accountId; } @Override @SuppressWarnings("rawtypes") public Object getAdapter(final Class adapter) { return null; } @Override public boolean exists() { return true; } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_TABLE); } public String getTableName() { return this.tableName; } @Override public String getName() { return this.tableName; } @Override public IPersistableElement getPersistable() { return null; } @Override public String getToolTipText() { return "Amazon DynamoDB Table Editor - " + this.tableName; } }
7,159
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/EditedItem.java
/* * Copyright 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.dynamodb.editor; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.eclipse.swt.widgets.TableItem; import com.amazonaws.services.dynamodbv2.model.AttributeValue; /** * An edited DynamoDB item in the table editor. */ class EditedItem { private final Set<String> editedAttributes = new HashSet<>(); private Map<String, AttributeValue> attributes; private final TableItem tableItem; public EditedItem(Map<String, AttributeValue> attributes, TableItem tableItem) { this.attributes = attributes; this.tableItem = tableItem; } public Map<String, AttributeValue> getAttributes() { return attributes; } public void setAttributes(Map<String, AttributeValue> attributes) { this.attributes = attributes; } public Set<String> getEditedAttributes() { return editedAttributes; } public void markAttributeEdited(String attributeName) { editedAttributes.add(attributeName); } public TableItem getTableItem() { return tableItem; } }
7,160
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/dynamodb/editor/AttributeValueUtil.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.dynamodb.editor; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.amazonaws.services.dynamodbv2.document.internal.InternalUtils; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.json.Jackson; /** * Utility methods for working with attribute values */ public class AttributeValueUtil { /** * Data type constants corresponding to the six fields of the * {@link AttributeValue} object. */ static final int S = 0; static final int SS = 1; static final int N = 2; static final int NS = 3; static final int B = 4; static final int BS = 5; /** * Sets exactly one field of the {@link AttributeValue} given, clearing all * others. The field set is determined by the datatype. */ static void setAttribute(AttributeValue attributeValue, final Collection<String> newValue, int dataType) { clearAttributes(attributeValue); if ( newValue.isEmpty() ) return; switch (dataType) { case NS: attributeValue.setNS(newValue); break; case SS: attributeValue.setSS(newValue); break; case BS: attributeValue.setBS(getByteBuffers(newValue)); break; case N: attributeValue.setN(newValue.iterator().next()); break; case S: attributeValue.setS(newValue.iterator().next()); break; case B: attributeValue.setB(getByteBuffer(newValue.iterator().next())); break; default: throw new RuntimeException("Unknown data type " + dataType); } } /** * Gets a byte buffer corresponding to the base64 string given. */ private static ByteBuffer getByteBuffer(String base64) { byte[] binary = BinaryUtils.fromBase64(base64); return ByteBuffer.wrap(binary); } /** * Returns a list of ByteBuffers corresponding to the base64 strings given. */ private static Collection<ByteBuffer> getByteBuffers(Collection<String> newValue) { List<ByteBuffer> buffers = new LinkedList<>(); for (String value : newValue) { buffers.add(getByteBuffer(value)); } return buffers; } static void setAttribute(AttributeValue attributeValue, final Collection<String> newValue, String dataType) { if ( ScalarAttributeType.N.toString().equals(dataType) ) { setAttribute(attributeValue, newValue, N); } else if ( ScalarAttributeType.S.toString().equals(dataType) ) { setAttribute(attributeValue, newValue, S); } else if ( ScalarAttributeType.B.toString().equals(dataType) ) { setAttribute(attributeValue, newValue, B); } else { throw new RuntimeException("Unknown data type " + dataType); } } /** * Translates the data types returned by some Dynamo apis into the integers * used by this class. */ static int getDataType(String dataType) { if ( ScalarAttributeType.S.toString().equals(dataType) ) { return S; } else if ( ScalarAttributeType.N.toString().equals(dataType) ) { return N; } else if ( ScalarAttributeType.B.toString().equals(dataType) ) { return B; } else if ( "SS".equals(dataType) ) { return SS; } else if ( "NS".equals(dataType) ) { return NS; } else if ( "BS".equals(dataType) ) { return BS; } else { throw new RuntimeException("Unknown data type " + dataType); } } /** * Clears all fields from the object given. */ static void clearAttributes(AttributeValue attributeValue) { attributeValue.setSS(null); attributeValue.setNS(null); attributeValue.setS(null); attributeValue.setN(null); attributeValue.setB(null); attributeValue.setBS(null); } /** * Formats the value of the given {@link AttributeValue} for display, * joining list elements with a comma and enclosing them in brackets. */ static String format(final AttributeValue value) { if ( value == null ) return ""; if ( value.getN() != null ) return value.getN(); else if ( value.getNS() != null ) return join(value.getNS()); else if ( value.getS() != null ) return value.getS(); else if ( value.getSS() != null ) return join(value.getSS(), true); else if ( value.getB() != null ) return base64Format(value.getB()); else if ( value.getBS() != null ) return joinBase64(value.getBS()); else if ( value.getBOOL() != null ) return value.getBOOL() ? "true" : "false"; else if ( value.getNULL() != null ) return value.getNULL() ? "null" : ""; else if ( value.getM() != null ) return formatMapAttribute(value.getM()); else if ( value.getL() != null ) return formatListAttribute(value.getL()); return ""; } private static String formatMapAttribute(Map<String, AttributeValue> map) { if (map == null) return ""; try { Map<String, Object> objectMap = InternalUtils.toSimpleMapValue(map); return Jackson.toJsonString(objectMap); } catch (Exception e) { return "A map of " + map.size() + " entries"; } } private static String formatListAttribute(List<AttributeValue> list) { if (list == null) return ""; try { List<Object> objectList = InternalUtils.toSimpleListValue(list); return Jackson.toJsonString(objectList); } catch (Exception e) { return "A list of " + list.size() + " entries"; } } /** * Returns the given byte buffer list as a base-64 formatted list */ private static String joinBase64(List<ByteBuffer> bs) { Collection<String> base64Strings = base64FormatOfBinarySet(bs); return join(base64Strings); } /** * Returns a base-64 string of the given bytes */ private static String base64Format(ByteBuffer b) { return BinaryUtils.toBase64(b.array()); } /** * Returns a base-64 string of the given bytes */ private static Collection<String> base64FormatOfBinarySet(Collection<ByteBuffer> bs) { List<String> base64Strings = new LinkedList<>(); for (ByteBuffer b : bs) { base64Strings.add(base64Format(b)); } return base64Strings; } /** * Joins a collection of values with commas, enclosed by brackets. An empty * or null set of values returns the empty string. */ static String join(final Collection<String> values) { return join(values, false); } /** * Joins a collection of values with commas, enclosed by brackets. An empty * or null set of values returns the empty string. * * @param quoted * Whether each value should be quoted in the output. */ static String join(final Collection<String> values, boolean quoted) { if ( values == null || values.isEmpty() ) { return ""; } StringBuilder builder = new StringBuilder("{"); boolean seenOne = false; for ( String s : values ) { if ( seenOne ) { builder.append(","); } else { seenOne = true; } builder.append(quoted ? "\"" + s + "\"" : s); } builder.append("}"); return builder.toString(); } /** * Returns the values from this {@link AttributeValue} as a collection, * which may contain only one element or be empty. */ static Collection<String> getValuesFromAttribute(AttributeValue value) { if ( value == null ) return Collections.emptyList(); if ( value.getN() != null ) { return Arrays.asList(value.getN()); } else if ( value.getNS() != null ) { return value.getNS(); } else if ( value.getS() != null ) { return Arrays.asList(value.getS()); } else if ( value.getSS() != null ) { return value.getSS(); } else if ( value.getB() != null ) { return Arrays.asList(base64Format(value.getB())); } else if ( value.getBS() != null ) { return base64FormatOfBinarySet(value.getBS()); } else { return Collections.emptyList(); } } /** * Validates the user input of a scalar attribute value. */ public static boolean validateScalarAttributeInput(String attributeInput, int dataType, boolean acceptEmpty) { if ( null == attributeInput ) { return false; } if ( attributeInput.isEmpty() ) { return acceptEmpty; } if ( dataType == S ) { return attributeInput.length() > 0; } else if ( dataType == N ) { return validateNumberStringInput(attributeInput); } else if ( dataType == B ) { return validateBase64StringInput(attributeInput); } else { return false; } } /** * Returns the warning message for the given attribute type. */ public static String getScalarAttributeValidationWarning(String attributeName, int dataType) { if ( dataType == S ) { return "Invalid String value for " + attributeName + "."; } else if ( dataType == N ) { return "Invalid Number value for " + attributeName + "."; } else if ( dataType == B ) { return "Invalid Base64 string for " + attributeName + "."; } else { return ""; } } /** * Validates the user input of Base64 string. */ private static boolean validateBase64StringInput(String base64) { byte[] decoded = BinaryUtils.fromBase64(base64); String encodedAgain = BinaryUtils.toBase64(decoded); return base64.equals(encodedAgain); } /** * Validates the user input of a number. */ private static boolean validateNumberStringInput(String number) { try { new BigInteger(number, 10); } catch ( NumberFormatException e ) { return false; } return true; } }
7,161
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/CreateTablePageUtil.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.dynamodb; import java.util.List; 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.Group; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; /** Some utility methods that could be shared by different CreateTable pages. **/ public class CreateTablePageUtil { public static Text newTextField(Composite comp) { Text text = new Text(comp, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(text); return text; } public static Link newLink(Listener linkListener, String linkText, Composite composite) { Link link = new Link(composite, SWT.WRAP); link.setText(linkText); link.addListener(SWT.Selection, linkListener); GridData data = new GridData(SWT.FILL, SWT.TOP, false, false); data.horizontalSpan = 3; link.setLayoutData(data); return link; } public static Group newGroup(Composite composite, String text, int columns) { Group group = new Group(composite, SWT.NONE); group.setText(text + ":"); group.setLayout(new GridLayout(columns, false)); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalSpan = 2; group.setLayoutData(gridData); return group; } public static String stringJoin(List<String> stringList, String delimiter) { if (stringList == null) return ""; StringBuilder sb = new StringBuilder(); String loopDelimiter = ""; for(String s : stringList) { sb.append(loopDelimiter); sb.append(s); loopDelimiter = delimiter; } return sb.toString(); } }
7,162
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/CreateTableFirstPage.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.dynamodb; 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.layout.GridLayoutFactory; 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.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.NotEmptyValidator; import com.amazonaws.eclipse.databinding.RangeValidator; public class CreateTableFirstPage extends WizardPage { private final String OK_MESSAGE = "Configure new DynamoDB table"; private boolean usesRangeKey = false; private Font italicFont; private IObservableValue tableName; private IObservableValue hashKeyName; private IObservableValue hashKeyType; private IObservableValue enableRangeKey; private IObservableValue rangeKeyName; private IObservableValue rangeKeyType; private IObservableValue readCapacity; private IObservableValue writeCapacity; private final DataBindingContext bindingContext = new DataBindingContext(); @Override public void dispose() { if (italicFont != null) italicFont.dispose(); super.dispose(); } private static final long CAPACITY_UNIT_MINIMUM = 1; private static final String[] DATA_TYPE_STRINGS = new String[] { "String", "Number", "Binary" }; CreateTableFirstPage(CreateTableWizard wizard) { super("Configure table"); setMessage(OK_MESSAGE); setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO)); tableName = PojoObservables.observeValue(wizard.getDataModel(), "tableName"); hashKeyName = PojoObservables.observeValue(wizard.getDataModel(), "hashKeyName"); hashKeyType = PojoObservables.observeValue(wizard.getDataModel(), "hashKeyType"); enableRangeKey = PojoObservables.observeValue(wizard.getDataModel(), "enableRangeKey"); rangeKeyName = PojoObservables.observeValue(wizard.getDataModel(), "rangeKeyName"); rangeKeyType = PojoObservables.observeValue(wizard.getDataModel(), "rangeKeyType"); readCapacity = PojoObservables.observeValue(wizard.getDataModel(), "readCapacity"); writeCapacity = PojoObservables.observeValue(wizard.getDataModel(), "writeCapacity"); } @Override public void createControl(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(comp); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(comp); // Table name Label tableNameLabel = new Label(comp, SWT.READ_ONLY); tableNameLabel.setText("Table Name:"); final Text tableNameText = CreateTablePageUtil.newTextField(comp); bindingContext.bindValue(SWTObservables.observeText(tableNameText, SWT.Modify), tableName); ChainValidator<String> tableNameValidationStatusProvider = new ChainValidator<>(tableName, new NotEmptyValidator("Please provide a table name")); bindingContext.addValidationStatusProvider(tableNameValidationStatusProvider); // Hash key Group hashKeyGroup = CreateTablePageUtil.newGroup(comp, "Hash Key", 2); new Label(hashKeyGroup, SWT.READ_ONLY).setText("Hash Key Name:"); final Text hashKeyText = CreateTablePageUtil.newTextField(hashKeyGroup); bindingContext.bindValue(SWTObservables.observeText(hashKeyText, SWT.Modify), hashKeyName); ChainValidator<String> hashKeyNameValidationStatusProvider = new ChainValidator<>(hashKeyName, new NotEmptyValidator("Please provide an attribute name for the hash key")); bindingContext.addValidationStatusProvider(hashKeyNameValidationStatusProvider); new Label(hashKeyGroup, SWT.READ_ONLY).setText("Hash Key Type:"); final Combo hashKeyTypeCombo = new Combo(hashKeyGroup, SWT.DROP_DOWN | SWT.READ_ONLY); hashKeyTypeCombo.setItems(DATA_TYPE_STRINGS); bindingContext.bindValue(SWTObservables.observeSelection(hashKeyTypeCombo), hashKeyType); hashKeyTypeCombo.select(0); // Range key Group rangeKeyGroup = CreateTablePageUtil.newGroup(comp, "Range Key", 2); final Button enableRangeKeyButton = new Button(rangeKeyGroup, SWT.CHECK); enableRangeKeyButton.setText("Enable Range Key"); GridDataFactory.fillDefaults().span(2, 1).applyTo(enableRangeKeyButton); bindingContext.bindValue(SWTObservables.observeSelection(enableRangeKeyButton), enableRangeKey); final Label rangeKeyAttributeLabel = new Label(rangeKeyGroup, SWT.READ_ONLY); rangeKeyAttributeLabel.setText("Range Key Name:"); final Text rangeKeyText = CreateTablePageUtil.newTextField(rangeKeyGroup); bindingContext.bindValue(SWTObservables.observeText(rangeKeyText, SWT.Modify), rangeKeyName); ChainValidator<String> rangeKeyNameValidationStatusProvider = new ChainValidator<>(rangeKeyName, enableRangeKey, new NotEmptyValidator( "Please provide an attribute name for the range key")); bindingContext.addValidationStatusProvider(rangeKeyNameValidationStatusProvider); final Label rangeKeyTypeLabel = new Label(rangeKeyGroup, SWT.READ_ONLY); rangeKeyTypeLabel.setText("Range Key Type:"); final Combo rangeKeyTypeCombo = new Combo(rangeKeyGroup, SWT.DROP_DOWN | SWT.READ_ONLY); rangeKeyTypeCombo.setItems(DATA_TYPE_STRINGS); bindingContext.bindValue(SWTObservables.observeSelection(rangeKeyTypeCombo), rangeKeyType); rangeKeyTypeCombo.select(0); enableRangeKeyButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { usesRangeKey = enableRangeKeyButton.getSelection(); rangeKeyAttributeLabel.setEnabled(usesRangeKey); rangeKeyText.setEnabled(usesRangeKey); rangeKeyTypeLabel.setEnabled(usesRangeKey); rangeKeyTypeCombo.setEnabled(usesRangeKey); } }); enableRangeKeyButton.setSelection(false); rangeKeyAttributeLabel.setEnabled(usesRangeKey); rangeKeyText.setEnabled(usesRangeKey); rangeKeyTypeLabel.setEnabled(usesRangeKey); rangeKeyTypeCombo.setEnabled(usesRangeKey); FontData[] fontData = tableNameLabel.getFont().getFontData(); for (FontData fd : fontData) { fd.setStyle(SWT.ITALIC); } italicFont = new Font(Display.getDefault(), fontData); // Table throughput Group throughputGroup = CreateTablePageUtil.newGroup(comp, "Table Throughput", 3); new Label(throughputGroup, SWT.READ_ONLY).setText("Read Capacity Units:"); final Text readCapacityText = CreateTablePageUtil.newTextField(throughputGroup); readCapacityText.setText("" + CAPACITY_UNIT_MINIMUM); bindingContext.bindValue(SWTObservables.observeText(readCapacityText, SWT.Modify), readCapacity); ChainValidator<Long> readCapacityValidationStatusProvider = new ChainValidator<>( readCapacity, new RangeValidator( "Please enter a read capacity of " + CAPACITY_UNIT_MINIMUM + " or more.", CAPACITY_UNIT_MINIMUM, Long.MAX_VALUE)); bindingContext.addValidationStatusProvider(readCapacityValidationStatusProvider); Label minimumReadCapacityLabel = new Label(throughputGroup, SWT.READ_ONLY); minimumReadCapacityLabel.setText("(Minimum capacity " + CAPACITY_UNIT_MINIMUM + ")"); minimumReadCapacityLabel.setFont(italicFont); new Label(throughputGroup, SWT.READ_ONLY).setText("Write Capacity Units:"); final Text writeCapacityText = CreateTablePageUtil.newTextField(throughputGroup); writeCapacityText.setText("" + CAPACITY_UNIT_MINIMUM); Label minimumWriteCapacityLabel = new Label(throughputGroup, SWT.READ_ONLY); minimumWriteCapacityLabel.setText("(Minimum capacity " + CAPACITY_UNIT_MINIMUM + ")"); minimumWriteCapacityLabel.setFont(italicFont); bindingContext.bindValue(SWTObservables.observeText(writeCapacityText, SWT.Modify), writeCapacity); ChainValidator<Long> writeCapacityValidationStatusProvider = new ChainValidator<>( writeCapacity, new RangeValidator( "Please enter a write capacity of " + CAPACITY_UNIT_MINIMUM + " or more.", CAPACITY_UNIT_MINIMUM, Long.MAX_VALUE)); bindingContext.addValidationStatusProvider(writeCapacityValidationStatusProvider); final Label throughputCapacityLabel = new Label(throughputGroup, SWT.WRAP); throughputCapacityLabel .setText("Amazon DynamoDB will reserve the necessary machine resources to meet your throughput needs based on the read and write capacity specified with consistent, low-latency performance. You pay a flat, hourly rate based on the capacity you reserve."); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalSpan = 3; gridData.widthHint = 200; throughputCapacityLabel.setLayoutData(gridData); throughputCapacityLabel.setFont(italicFont); // Help info String pricingLinkText = "<a href=\"" + "http://aws.amazon.com/dynamodb/#pricing" + "\">" + "More information on Amazon DynamoDB pricing</a>. "; CreateTablePageUtil.newLink(new WebLinkListener(), pricingLinkText, throughputGroup); // 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,163
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/DynamoDBContentProvider.java
package com.amazonaws.eclipse.explorer.dynamodb; import java.util.LinkedList; import java.util.List; import org.eclipse.swt.widgets.Display; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.explorer.AWSResourcesRootElement; import com.amazonaws.eclipse.explorer.AbstractContentProvider; import com.amazonaws.eclipse.explorer.Loading; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.ListTablesRequest; import com.amazonaws.services.dynamodbv2.model.ListTablesResult; import com.amazonaws.services.dynamodbv2.model.TableStatus; public class DynamoDBContentProvider extends AbstractContentProvider { private static final long tableStatusRefreshDelay = 5 * 1000; private static DynamoDBContentProvider instance; public DynamoDBContentProvider() { /* Sets the background job that updates the table status. */ setBackgroundJobFactory(new BackgroundContentUpdateJobFactory() { @Override protected synchronized boolean executeBackgroundJob(final Object parentElement) throws AmazonClientException { if ( null == cachedResponses || cachedResponses.isEmpty() || null == cachedResponses.get(parentElement) ) { return false; } AmazonDynamoDB dynamoDBClient = AwsToolkitCore.getClientFactory().getDynamoDBV2Client(); Object[] nodes = cachedResponses.get(parentElement); boolean refreshUI = false; boolean shouldKeepRunning = false; for ( Object node : nodes ) { DynamoDBTableNode dynamoDBNode; if ( node instanceof DynamoDBTableNode ) { dynamoDBNode = (DynamoDBTableNode) node; } else { continue; } if ( dynamoDBNode.getTableStatus() != TableStatus.ACTIVE ) { TableStatus updatedStatus; try { updatedStatus = TableStatus.valueOf(dynamoDBClient .describeTable( new DescribeTableRequest() .withTableName(dynamoDBNode .getTableName())).getTable() .getTableStatus()); } catch ( AmazonServiceException ase ) { if (ase.getErrorCode().equalsIgnoreCase( "ResourceNotFoundException") == true) { /* Refresh both the cache and UI when a table node has already been deleted. */ refresh(); return false; } else { throw ase; } } catch ( IllegalArgumentException iae ) { throw new AmazonClientException("Unrecognized table status string.", iae); } /* Only refresh UI when some status has changed */ if ( updatedStatus != dynamoDBNode.getTableStatus() ) { dynamoDBNode.setTableStatus(updatedStatus); refreshUI = true; } if ( updatedStatus != TableStatus.ACTIVE ) { shouldKeepRunning = true; } } } if ( refreshUI ) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { viewer.refresh(parentElement); } }); } return shouldKeepRunning; } @Override protected long getRefreshDelay() { return tableStatusRefreshDelay; } }); instance = this; } public static DynamoDBContentProvider getInstance() { return instance; } @Override public boolean hasChildren(Object element) { return element instanceof AWSResourcesRootElement || element instanceof DynamoDBRootNode; } @Override public Object[] loadChildren(Object parentElement) { if ( parentElement instanceof AWSResourcesRootElement) { return new Object[] { DynamoDBRootNode.NODE }; } if ( parentElement == DynamoDBRootNode.NODE) { new DataLoaderThread(parentElement) { @Override public Object[] loadData() { AmazonDynamoDB db = AwsToolkitCore.getClientFactory().getDynamoDBV2Client(); List<DynamoDBTableNode> nodes = new LinkedList<>(); ListTablesResult listTables = new ListTablesResult(); do { listTables = db.listTables(new ListTablesRequest().withExclusiveStartTableName(listTables .getLastEvaluatedTableName())); for ( String tableName : listTables.getTableNames() ) { /* Defer getting the table status */ nodes.add(new DynamoDBTableNode(tableName, null)); } } while ( listTables.getLastEvaluatedTableName() != null ); return nodes.toArray(); } }.start(); } return Loading.LOADING; } @Override public String getServiceAbbreviation() { return ServiceAbbreviations.DYNAMODB; } }
7,164
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/DynamoDBTableNode.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.dynamodb; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import com.amazonaws.AmazonServiceException; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.eclipse.dynamodb.editor.OpenTableEditorAction; import com.amazonaws.eclipse.explorer.ExplorerNode; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.TableStatus; public class DynamoDBTableNode extends ExplorerNode { private final String tableName; private TableStatus tableStatus; public String getTableName() { return tableName; } public TableStatus getTableStatus() { return tableStatus; } /** * Sets the status of the table that this node represents, and changes to * the corresponding open action. */ public void setTableStatus(final TableStatus tableStatus) { this.tableStatus = tableStatus; if ( tableStatus == null ) { setOpenAction(new Action() { @Override public void run() { /* * Update the table status immediately when the node is * being opened, but has not been set with table status. */ AmazonDynamoDB dynamoDBClient = AwsToolkitCore.getClientFactory().getDynamoDBV2Client(); boolean describeTableError = false; TableStatus updatedStatus = null; try { updatedStatus = TableStatus.valueOf(dynamoDBClient .describeTable( new DescribeTableRequest() .withTableName(tableName)).getTable() .getTableStatus()); } catch ( AmazonServiceException ase ) { if (ase.getErrorCode().equalsIgnoreCase( "ResourceNotFoundException") == true) { /* Show warning that the table has already been deleted */ MessageDialog dialog = new MessageDialog( Display.getCurrent().getActiveShell(), "Cannot open this table", AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON), "Table has been deleted.", MessageDialog.ERROR, new String[] { "OK" }, 0); dialog.open(); /* * We need to explicitly refresh the tree view if a * table node has already been deleted in DynamoDB */ DynamoDBContentProvider.getInstance().refresh(); return; } else { describeTableError = true; } } catch ( IllegalArgumentException iae ) { /* Unrecognized table status */ describeTableError = true; } if ( describeTableError ) { /* * Still allow the user to open the table editor if we * cannot get the table status now. (But the background * job will still keep trying to update the table * status). */ setOpenAction(new OpenTableEditorAction(tableName)); return; } /* assert: updatedStatus != null */ setTableStatus(updatedStatus); DynamoDBTableNode.this.getOpenAction().run(); } }); } else if ( tableStatus == TableStatus.ACTIVE ) { /* * Open the table editor only when the node is in ACTIVE status. */ setOpenAction(new OpenTableEditorAction(tableName)); } else { /* * For CREATING/DELETING/UPDATING, suppress opening the table editor. * Show a warning on the table status instead. */ setOpenAction(new Action() { @Override public void run() { /* Show the warning that the table is CREATING/DELETING/UPDATING */ MessageDialog dialog = new MessageDialog( Display.getCurrent().getActiveShell(), "Cannot open this table", AwsToolkitCore.getDefault() .getImageRegistry() .get(AwsToolkitCore.IMAGE_AWS_ICON), "Cannot open this table(" + tableName + "), since it is in the status of " + tableStatus + ".", MessageDialog.ERROR, new String[] { "OK" }, 0); dialog.open(); } }); } } public DynamoDBTableNode(String tableName) { this(tableName, null); } public DynamoDBTableNode(String tableName, TableStatus tableStatus) { super(tableName, 0, DynamoDBPlugin.getDefault().getImageRegistry() .get(DynamoDBPlugin.IMAGE_TABLE), null); this.tableName = tableName; setTableStatus(tableStatus); } }
7,165
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/CreateTableWizard.java
/* * Copyright 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.explorer.dynamodb; import java.util.HashMap; import java.util.LinkedList; 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.core.runtime.jobs.Job; import org.eclipse.jface.wizard.Wizard; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; /** * Wizard to create a new DynamoDB table. */ class CreateTableWizard extends Wizard { // Map the UI text value to that for creating table request private Map<String, String> UINameToValueMap; private CreateTableFirstPage firstPage; private CreateTableSecondPage secondPage; private CreateTableDataModel dataModel; public CreateTableWizard() { init(); setNeedsProgressMonitor(true); setWindowTitle("Create New DynamoDB Table"); dataModel = new CreateTableDataModel(); } @Override public void addPages() { firstPage = new CreateTableFirstPage(this); addPage(firstPage); secondPage = new CreateTableSecondPage(this); addPage(secondPage); } @Override public boolean performFinish() { final String accountId = AwsToolkitCore.getDefault().getCurrentAccountId(); final AmazonDynamoDB dynamoDBClient = AwsToolkitCore.getClientFactory(accountId).getDynamoDBV2Client(); final CreateTableRequest createTableRequest = generateCreateTableRequest(); new Job("Creating table") { @Override protected IStatus run(IProgressMonitor monitor) { try { dynamoDBClient.createTable(createTableRequest); return Status.OK_STATUS; } catch (Exception e) { return new Status(Status.ERROR, DynamoDBPlugin.getDefault().getPluginId(), "Unable to create the table: " + e.getMessage(), e); } } }.schedule(); return true; } public CreateTableDataModel getDataModel() { return dataModel; } /** Clear and then collect all the AttributeDefinitions defined in the primary table and each index */ public void collectAllAttribtueDefinitions() { dataModel.getAttributeDefinitions().clear(); // Primary keys dataModel.getAttributeDefinitions().add(new AttributeDefinition().withAttributeName(dataModel.getHashKeyName()).withAttributeType(dataModel.getHashKeyType())); if (dataModel.getEnableRangeKey()) { dataModel.getAttributeDefinitions().add(new AttributeDefinition().withAttributeName(dataModel.getRangeKeyName()).withAttributeType(dataModel.getRangeKeyType())); } // Index keys defined in the second page dataModel.getAttributeDefinitions().addAll(secondPage.getAllIndexKeyAttributeDefinitions()); } private CreateTableRequest generateCreateTableRequest() { preProcessDataModel(); CreateTableRequest createTableRequest = new CreateTableRequest(); createTableRequest.setTableName(dataModel.getTableName()); ProvisionedThroughput throughput = new ProvisionedThroughput(); throughput.setReadCapacityUnits(dataModel.getReadCapacity()); throughput.setWriteCapacityUnits(dataModel.getWriteCapacity()); createTableRequest.setProvisionedThroughput(throughput); List<KeySchemaElement> keySchema = new LinkedList<>(); KeySchemaElement keySchemaElement = new KeySchemaElement(); keySchemaElement.setAttributeName(dataModel.getHashKeyName()); keySchemaElement.setKeyType(KeyType.HASH); keySchema.add(keySchemaElement); if (dataModel.getEnableRangeKey()) { keySchemaElement = new KeySchemaElement(); keySchemaElement.setAttributeName(dataModel.getRangeKeyName()); keySchemaElement.setKeyType(KeyType.RANGE); keySchema.add(keySchemaElement); } createTableRequest.setKeySchema(keySchema); createTableRequest.setAttributeDefinitions(dataModel.getAttributeDefinitions()); if ( dataModel.getLocalSecondaryIndexes() != null && ( !dataModel.getLocalSecondaryIndexes().isEmpty() ) ) { createTableRequest.setLocalSecondaryIndexes(dataModel.getLocalSecondaryIndexes()); } if ( dataModel.getGlobalSecondaryIndexes() != null && ( !dataModel.getGlobalSecondaryIndexes().isEmpty() ) ) { createTableRequest.setGlobalSecondaryIndexes(dataModel.getGlobalSecondaryIndexes()); } System.out.println(createTableRequest); return createTableRequest; } /** * Collect all the attribute definitions from primary table and secondary * index, then convert the string value shown in UI to the that for the * creating table request. */ private void preProcessDataModel() { collectAllAttribtueDefinitions(); for (AttributeDefinition attribute : dataModel.getAttributeDefinitions()) { attribute.setAttributeType(UINameToValueMap.get(attribute.getAttributeType())); } if (null != dataModel.getLocalSecondaryIndexes()) { for (LocalSecondaryIndex index : dataModel.getLocalSecondaryIndexes()) { index.getProjection().setProjectionType(UINameToValueMap.get(index.getProjection().getProjectionType())); } } if (null != dataModel.getGlobalSecondaryIndexes()) { for (GlobalSecondaryIndex index : dataModel.getGlobalSecondaryIndexes()) { index.getProjection().setProjectionType(UINameToValueMap.get(index.getProjection().getProjectionType())); } } } private void init() { UINameToValueMap = new HashMap<>(); UINameToValueMap.put("String", "S"); UINameToValueMap.put("Number", "N"); UINameToValueMap.put("Binary", "B"); UINameToValueMap.put("All Attributes", "ALL"); UINameToValueMap.put("Table and Index Keys", "KEYS_ONLY"); UINameToValueMap.put("Specify Attributes", "INCLUDE"); } }
7,166
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/DynamoDBRootNode.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.dynamodb; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.eclipse.explorer.ExplorerNode; /** * Root node for DynamoDB resources in the AWS explorer */ public class DynamoDBRootNode extends ExplorerNode { public static final DynamoDBRootNode NODE = new DynamoDBRootNode(); private DynamoDBRootNode() { super("Amazon DynamoDB", 1, DynamoDBPlugin.getDefault().getImageRegistry().get(DynamoDBPlugin.IMAGE_DYNAMODB_SERVICE)); } }
7,167
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/CreateTableDataModel.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.dynamodb; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex; /** * A POJO model containing all the data for a CreateTable request. * This class is used as the model side of a data-binding. */ public class CreateTableDataModel { private String tableName; private String hashKeyName; private String hashKeyType; // Whether there is a range key private boolean enableRangeKey; private String rangeKeyName; private String rangeKeyType; private Long readCapacity; private Long writeCapacity; private List<LocalSecondaryIndex> localSecondaryIndexes; private List<GlobalSecondaryIndex> globalSecondaryIndexes; // We use a set instead of a list to store all the attribute definitions, // in order to avoid duplicate from multiple secondary indexes. private Set<AttributeDefinition> attributeDefinitions = new HashSet<>(); public void setTableName(String tableName) { this.tableName = tableName; } public String getTableName() { return tableName; } public void setHashKeyName(String hashKeyName) { this.hashKeyName = hashKeyName; } public String getHashKeyName() { return hashKeyName; } public void setHashKeyType(String hashKeyType) { this.hashKeyType = hashKeyType; } public String getHashKeyType() { return hashKeyType; } public void setReadCapacity(Long readCapacity) { this.readCapacity = readCapacity; } public Long getReadCapacity() { return readCapacity; } public Long getWriteCapacity() { return writeCapacity; } public void setWriteCapacity(Long writeCapacity) { this.writeCapacity = writeCapacity; } public void setEnableRangeKey(boolean enableRangeKey) { this.enableRangeKey = enableRangeKey; } public boolean getEnableRangeKey() { return enableRangeKey; } public void setRangeKeyName(String rangeKeyName) { this.rangeKeyName = rangeKeyName; } public String getRangeKeyName() { return rangeKeyName; } public void setRangeKeyType(String rangeKeyType) { this.rangeKeyType = rangeKeyType; } public String getRangeKeyType() { return rangeKeyType; } public List<LocalSecondaryIndex> getLocalSecondaryIndexes() { return localSecondaryIndexes; } public void setLocalSecondaryIndexes(List<LocalSecondaryIndex> localSecondaryIndexes) { this.localSecondaryIndexes = localSecondaryIndexes; } public List<GlobalSecondaryIndex> getGlobalSecondaryIndexes() { return globalSecondaryIndexes; } public void setGlobalSecondaryIndexes( List<GlobalSecondaryIndex> globalSecondaryIndexes) { this.globalSecondaryIndexes = globalSecondaryIndexes; } public Set<AttributeDefinition> getAttributeDefinitions() { return attributeDefinitions; } public void setAttributeDefinitions(Set<AttributeDefinition> attributeDefinitions) { this.attributeDefinitions = attributeDefinitions; } public List<AttributeDefinition> getAttributeDefinitionsAsUnmodifiableList() { List<AttributeDefinition> defList = Collections.unmodifiableList(new LinkedList<AttributeDefinition>()); defList.addAll(attributeDefinitions); return defList; } }
7,168
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/DynamoDBTableNodeDecorator.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.dynamodb; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ILightweightLabelDecorator; import com.amazonaws.services.dynamodbv2.model.TableStatus; public class DynamoDBTableNodeDecorator implements ILightweightLabelDecorator { @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 void decorate(Object element, IDecoration decoration) { if (element instanceof DynamoDBTableNode) { DynamoDBTableNode dynamoDBTableNode = (DynamoDBTableNode)element; TableStatus tableStatus = dynamoDBTableNode.getTableStatus(); if ( null != tableStatus ) { decoration.addSuffix(" (" + tableStatus.toString() + ")"); } } } }
7,169
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/AddGSIDialog.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.dynamodb; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; 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.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.databinding.viewers.ObservableListContentProvider; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.NotEmptyValidator; import com.amazonaws.eclipse.databinding.RangeValidator; import com.amazonaws.eclipse.dynamodb.AbstractAddNewAttributeDialog; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.Projection; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; public class AddGSIDialog extends TitleAreaDialog { /** Widget used as data-binding targets **/ private Text indexHashKeyNameText; private Combo indexHashKeyAttributeTypeCombo; private Button enableIndexRangeKeyButton; private Text indexRangeKeyNameText; private Combo indexRangeKeyAttributeTypeCombo; private Text indexNameText; private Combo projectionTypeCombo; private Button addAttributeButton; private Button okButton; /** The data objects that will be used to generate the service request **/ private final GlobalSecondaryIndex globalSecondaryIndex; private final KeySchemaElement indexRangeKeySchemaDefinition = new KeySchemaElement() .withAttributeName(null).withKeyType(KeyType.RANGE); private final AttributeDefinition indexHashKeyAttributeDefinition = new AttributeDefinition(); private final AttributeDefinition indexRangeKeyAttributeDefinition = new AttributeDefinition(); private boolean enableIndexRangeKey = false; private final DataBindingContext bindingContext = new DataBindingContext(); /** The model value objects for data-binding **/ private final IObservableValue indexNameModel; private final IObservableValue indexHashKeyNameInKeySchemaDefinitionModel; private final IObservableValue indexHashKeyNameInAttributeDefinitionsModel; private final IObservableValue indexHashKeyAttributeTypeModel; private final IObservableValue enableIndexRangeKeyModel; private final IObservableValue indexRangeKeyNameInKeySchemaDefinitionModel; private final IObservableValue indexRangeKeyNameInAttributeDefinitionsModel; private final IObservableValue indexRangeKeyAttributeTypeModel; private final IObservableValue projectionTypeModel; private final IObservableValue readCapacityModel; private final IObservableValue writeCapacityModel; /** The map from each primary key name to the combo index of its attribute type **/ private final Map<String, Integer> primaryKeyTypes = new HashMap<>(); private Font italicFont; private static final long CAPACITY_UNIT_MINIMUM = 1; private static final String[] DATA_TYPE_STRINGS = new String[] { "String", "Number", "Binary" }; private static final String[] PROJECTED_ATTRIBUTES = new String[] { "All Attributes", "Table and Index Keys", "Specify Attributes" }; public AddGSIDialog(Shell parentShell, CreateTableDataModel dataModel) { super(parentShell); // Initialize the variable necessary for data-binding globalSecondaryIndex = new GlobalSecondaryIndex(); // The index hash key to be defined by the user KeySchemaElement indexHashKeySchemaDefinition = new KeySchemaElement() .withAttributeName(null).withKeyType(KeyType.HASH); globalSecondaryIndex.withKeySchema(indexHashKeySchemaDefinition); globalSecondaryIndex.setProjection(new Projection()); globalSecondaryIndex.setProvisionedThroughput(new ProvisionedThroughput()); // Initialize IObservableValue objects that keep track of data variables indexNameModel = PojoObservables.observeValue(globalSecondaryIndex, "indexName"); indexHashKeyNameInKeySchemaDefinitionModel = PojoObservables.observeValue(indexHashKeySchemaDefinition, "attributeName"); indexHashKeyAttributeTypeModel = PojoObservables.observeValue(indexHashKeyAttributeDefinition, "attributeType"); indexHashKeyNameInAttributeDefinitionsModel = PojoObservables.observeValue(indexHashKeyAttributeDefinition, "attributeName"); enableIndexRangeKeyModel = PojoObservables.observeValue(this, "enableIndexRangeKey"); indexRangeKeyNameInKeySchemaDefinitionModel = PojoObservables.observeValue(indexRangeKeySchemaDefinition, "attributeName"); indexRangeKeyAttributeTypeModel = PojoObservables.observeValue(indexRangeKeyAttributeDefinition, "attributeType"); indexRangeKeyNameInAttributeDefinitionsModel = PojoObservables.observeValue(indexRangeKeyAttributeDefinition, "attributeName"); projectionTypeModel = PojoObservables.observeValue(globalSecondaryIndex.getProjection(), "projectionType"); readCapacityModel = PojoObservables.observeValue(globalSecondaryIndex.getProvisionedThroughput(), "readCapacityUnits"); writeCapacityModel = PojoObservables.observeValue(globalSecondaryIndex.getProvisionedThroughput(), "writeCapacityUnits"); // Get the information of the primary keys String primaryHashKeyName = dataModel.getHashKeyName(); int primaryHashKeyTypeComboIndex = Arrays.<String>asList(DATA_TYPE_STRINGS).indexOf(dataModel.getHashKeyType()); primaryKeyTypes.put(primaryHashKeyName, primaryHashKeyTypeComboIndex); if (dataModel.getEnableRangeKey()) { String primaryRangeKeyName = dataModel.getRangeKeyName(); int primaryRangeKeyTypeComboIndex = Arrays.<String>asList(DATA_TYPE_STRINGS).indexOf(dataModel.getRangeKeyType()); primaryKeyTypes.put(primaryRangeKeyName, primaryRangeKeyTypeComboIndex); } setShellStyle(SWT.RESIZE); } @Override protected Control createContents(Composite parent) { Control contents = super.createContents(parent); setTitle("Add Global Secondary Index"); setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO)); okButton = getButton(IDialogConstants.OK_ID); okButton.setEnabled(false); return contents; } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText("Add Global Secondary Index"); shell.setMinimumSize(400, 700); } @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(2, false)); // Index hash key attribute name Group indexHashKeyGroup = CreateTablePageUtil.newGroup(composite, "Index Hash Key", 2); new Label(indexHashKeyGroup, SWT.NONE | SWT.READ_ONLY).setText("Index Hash Key Name:"); indexHashKeyNameText = new Text(indexHashKeyGroup, SWT.BORDER); bindingContext.bindValue(SWTObservables.observeText(indexHashKeyNameText, SWT.Modify), indexHashKeyNameInKeySchemaDefinitionModel); ChainValidator<String> indexHashKeyNameValidationStatusProvider = new ChainValidator<>(indexHashKeyNameInKeySchemaDefinitionModel, new NotEmptyValidator("Please provide the index hash key name")); bindingContext.addValidationStatusProvider(indexHashKeyNameValidationStatusProvider); bindingContext.bindValue(SWTObservables.observeText(indexHashKeyNameText, SWT.Modify), indexHashKeyNameInAttributeDefinitionsModel); indexHashKeyNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (primaryKeyTypes.containsKey(indexHashKeyNameText.getText()) && indexHashKeyAttributeTypeCombo != null && primaryKeyTypes.get(indexHashKeyNameText.getText()) > -1) { indexHashKeyAttributeTypeCombo.select(primaryKeyTypes.get(indexHashKeyNameText.getText())); indexHashKeyAttributeTypeCombo.setEnabled(false); } else if (indexHashKeyAttributeTypeCombo != null) { indexHashKeyAttributeTypeCombo.setEnabled(true); } } }); GridDataFactory.fillDefaults().grab(true, false).applyTo(indexHashKeyNameText); // Index hash key attribute type new Label(indexHashKeyGroup, SWT.NONE | SWT.READ_ONLY).setText("Index Hash Key Type:"); indexHashKeyAttributeTypeCombo = new Combo(indexHashKeyGroup, SWT.DROP_DOWN | SWT.READ_ONLY); indexHashKeyAttributeTypeCombo.setItems(DATA_TYPE_STRINGS); indexHashKeyAttributeTypeCombo.select(0); bindingContext.bindValue(SWTObservables.observeSelection(indexHashKeyAttributeTypeCombo), indexHashKeyAttributeTypeModel); Group indexRangeKeyGroup = CreateTablePageUtil.newGroup(composite, "Index Range Key", 2); // Enable index range key button enableIndexRangeKeyButton = new Button(indexRangeKeyGroup, SWT.CHECK); enableIndexRangeKeyButton.setText("Enable Index Range Key"); GridDataFactory.fillDefaults().span(2, 1).applyTo(enableIndexRangeKeyButton); bindingContext.bindValue(SWTObservables.observeSelection(enableIndexRangeKeyButton), enableIndexRangeKeyModel); // Index range key attribute name final Label indexRangeKeyAttributeLabel = new Label(indexRangeKeyGroup, SWT.NONE | SWT.READ_ONLY); indexRangeKeyAttributeLabel.setText("Index Range Key Name:"); indexRangeKeyNameText = new Text(indexRangeKeyGroup, SWT.BORDER); bindingContext.bindValue(SWTObservables.observeText(indexRangeKeyNameText, SWT.Modify), indexRangeKeyNameInKeySchemaDefinitionModel); ChainValidator<String> indexRangeKeyNameValidationStatusProvider = new ChainValidator<>( indexRangeKeyNameInKeySchemaDefinitionModel, enableIndexRangeKeyModel, new NotEmptyValidator("Please provide the index range key name")); bindingContext.addValidationStatusProvider(indexRangeKeyNameValidationStatusProvider); bindingContext.bindValue(SWTObservables.observeText(indexRangeKeyNameText, SWT.Modify), indexRangeKeyNameInAttributeDefinitionsModel); indexRangeKeyNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (primaryKeyTypes.containsKey(indexRangeKeyNameText.getText()) && indexRangeKeyAttributeTypeCombo != null && primaryKeyTypes.get(indexRangeKeyNameText.getText()) > -1) { indexRangeKeyAttributeTypeCombo.select(primaryKeyTypes.get(indexRangeKeyNameText.getText())); indexRangeKeyAttributeTypeCombo.setEnabled(false); } else if (indexRangeKeyAttributeTypeCombo != null) { indexRangeKeyAttributeTypeCombo.setEnabled(true); } } }); GridDataFactory.fillDefaults().grab(true, false).applyTo(indexRangeKeyNameText); // Index range key attribute type final Label indexRangeKeyTypeLabel = new Label(indexRangeKeyGroup, SWT.NONE | SWT.READ_ONLY); indexRangeKeyTypeLabel.setText("Index Range Key Type:"); indexRangeKeyAttributeTypeCombo = new Combo(indexRangeKeyGroup, SWT.DROP_DOWN | SWT.READ_ONLY); indexRangeKeyAttributeTypeCombo.setItems(DATA_TYPE_STRINGS); indexRangeKeyAttributeTypeCombo.select(0); bindingContext.bindValue(SWTObservables.observeSelection(indexRangeKeyAttributeTypeCombo), indexRangeKeyAttributeTypeModel); enableIndexRangeKeyButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { enableIndexRangeKey = enableIndexRangeKeyButton.getSelection(); indexRangeKeyAttributeLabel.setEnabled(enableIndexRangeKey); indexRangeKeyNameText.setEnabled(enableIndexRangeKey); indexRangeKeyTypeLabel.setEnabled(enableIndexRangeKey); indexRangeKeyAttributeTypeCombo.setEnabled(enableIndexRangeKey); } }); enableIndexRangeKeyButton.setSelection(false); indexRangeKeyAttributeLabel.setEnabled(false); indexRangeKeyNameText.setEnabled(false); indexRangeKeyTypeLabel.setEnabled(false); indexRangeKeyAttributeTypeCombo.setEnabled(false); // Index name Label indexNameLabel = new Label(composite, SWT.NONE | SWT.READ_ONLY); indexNameLabel.setText("Index Name:"); indexNameText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(indexNameText); bindingContext.bindValue(SWTObservables.observeText(indexNameText, SWT.Modify), indexNameModel); ChainValidator<String> indexNameValidationStatusProvider = new ChainValidator<>(indexNameModel, new NotEmptyValidator("Please provide an index name")); bindingContext.addValidationStatusProvider(indexNameValidationStatusProvider); // Projection type new Label(composite, SWT.NONE | SWT.READ_ONLY).setText("Projected Attributes:"); projectionTypeCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY); projectionTypeCombo.setItems(PROJECTED_ATTRIBUTES); projectionTypeCombo.select(0); bindingContext.bindValue(SWTObservables.observeSelection(projectionTypeCombo), projectionTypeModel); projectionTypeCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (projectionTypeCombo.getSelectionIndex() == 2) { // Enable the list for adding non-key attributes to the projection addAttributeButton.setEnabled(true); } else { addAttributeButton.setEnabled(false); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); // Non-key attributes in the projection final AttributeList attributeList = new AttributeList(composite); GridDataFactory.fillDefaults().grab(true, true).hint(SWT.DEFAULT, SWT.DEFAULT).applyTo(attributeList); addAttributeButton = new Button(composite, SWT.PUSH); addAttributeButton.setText("Add Attribute"); addAttributeButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); addAttributeButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD)); addAttributeButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { AddNewAttributeDialog newAttributeTable = new AddNewAttributeDialog(); if (newAttributeTable.open() == 0) { // lazy-initialize the list if (null == globalSecondaryIndex.getProjection().getNonKeyAttributes()) { globalSecondaryIndex.getProjection().setNonKeyAttributes(new LinkedList<String>()); } globalSecondaryIndex.getProjection().getNonKeyAttributes().add(newAttributeTable.getNewAttributeName()); attributeList.refresh(); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); addAttributeButton.setEnabled(false); // GSI throughput FontData[] fontData = indexNameLabel.getFont().getFontData(); for (FontData fd : fontData) { fd.setStyle(SWT.ITALIC); } italicFont = new Font(Display.getDefault(), fontData); Group throughputGroup = CreateTablePageUtil.newGroup(composite, "Global Secondary Index Throughput", 3); new Label(throughputGroup, SWT.READ_ONLY).setText("Read Capacity Units:"); final Text readCapacityText = CreateTablePageUtil.newTextField(throughputGroup); readCapacityText.setText("" + CAPACITY_UNIT_MINIMUM); bindingContext.bindValue(SWTObservables.observeText(readCapacityText, SWT.Modify), readCapacityModel); ChainValidator<Long> readCapacityValidationStatusProvider = new ChainValidator<>( readCapacityModel, new RangeValidator( "Please enter a read capacity of " + CAPACITY_UNIT_MINIMUM + " or more.", CAPACITY_UNIT_MINIMUM, Long.MAX_VALUE)); bindingContext.addValidationStatusProvider(readCapacityValidationStatusProvider); Label minimumReadCapacityLabel = new Label(throughputGroup, SWT.READ_ONLY); minimumReadCapacityLabel.setText("(Minimum capacity " + CAPACITY_UNIT_MINIMUM + ")"); minimumReadCapacityLabel.setFont(italicFont); new Label(throughputGroup, SWT.READ_ONLY).setText("Write Capacity Units:"); final Text writeCapacityText = CreateTablePageUtil.newTextField(throughputGroup); writeCapacityText.setText("" + CAPACITY_UNIT_MINIMUM); Label minimumWriteCapacityLabel = new Label(throughputGroup, SWT.READ_ONLY); minimumWriteCapacityLabel.setText("(Minimum capacity " + CAPACITY_UNIT_MINIMUM + ")"); minimumWriteCapacityLabel.setFont(italicFont); bindingContext.bindValue(SWTObservables.observeText(writeCapacityText, SWT.Modify), writeCapacityModel); ChainValidator<Long> writeCapacityValidationStatusProvider = new ChainValidator<>( writeCapacityModel, new RangeValidator( "Please enter a write capacity of " + CAPACITY_UNIT_MINIMUM + " or more.", CAPACITY_UNIT_MINIMUM, Long.MAX_VALUE)); bindingContext.addValidationStatusProvider(writeCapacityValidationStatusProvider); final Label throughputCapacityLabel = new Label(throughputGroup, SWT.WRAP); throughputCapacityLabel .setText("This throughput is separate from and in addition to the primary table's throughput."); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalSpan = 3; gridData.widthHint = 200; throughputCapacityLabel.setLayoutData(gridData); throughputCapacityLabel.setFont(italicFont); // 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.getSeverity() == Status.ERROR) { setErrorMessage(status.getMessage()); if (okButton != null) { okButton.setEnabled(false); } } else { setErrorMessage(null); if (okButton != null) { okButton.setEnabled(true); } } } }); bindingContext.updateModels(); return composite; } /** This method should only be called once by the parent wizard. **/ public GlobalSecondaryIndex getGlobalSecondaryIndex() { if (enableIndexRangeKey) { globalSecondaryIndex.getKeySchema().add(indexRangeKeySchemaDefinition); } return globalSecondaryIndex; } /** * Returns an unmodifiable list of all the AttributeDefinition of the index keys associated with this GSI. */ public List<AttributeDefinition> getIndexKeyAttributeDefinitions() { List<AttributeDefinition> keyAttrs = new LinkedList<>(); keyAttrs.add(indexHashKeyAttributeDefinition); if (isEnableIndexRangeKey() ) { keyAttrs.add(indexRangeKeyAttributeDefinition); } return Collections.unmodifiableList(keyAttrs); } public boolean isEnableIndexRangeKey() { return enableIndexRangeKey; } public void setEnableIndexRangeKey(boolean enableIndexRangeKey) { this.enableIndexRangeKey = enableIndexRangeKey; } private class AddNewAttributeDialog extends AbstractAddNewAttributeDialog { @Override public void validate() { if (getButton(0) == null) return; if (getNewAttributeName().length() == 0) { getButton(0).setEnabled(false); return; } getButton(0).setEnabled(true); return; } } /** The list widget for adding projected non-key attributes. **/ private class AttributeList extends Composite { private ListViewer viewer; private AttributeListContentProvider attributeListContentProvider; public AttributeList(Composite parent) { super(parent, SWT.NONE); this.setLayout(new GridLayout()); viewer = new ListViewer(this, SWT.BORDER | SWT.V_SCROLL | SWT.READ_ONLY); attributeListContentProvider = new AttributeListContentProvider(); viewer.setContentProvider(attributeListContentProvider); viewer.setLabelProvider(new LabelProvider()); GridDataFactory.fillDefaults().grab(true, true).applyTo(viewer.getList()); viewer.getList().setVisible(true); MenuManager menuManager = new MenuManager("#PopupMenu"); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { if (viewer.getList().getSelectionCount() > 0) { manager.add(new Action() { @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE); } @Override public void run() { // In theory, this should never be null. if (null != globalSecondaryIndex.getProjection().getNonKeyAttributes()) { globalSecondaryIndex.getProjection().getNonKeyAttributes().remove(viewer.getList().getSelectionIndex()); } refresh(); } @Override public String getText() { return "Delete Attribute"; } }); } } }); viewer.getList().setMenu(menuManager.createContextMenu(viewer.getList())); } // Enforce to call getElements to update list public void refresh() { viewer.setInput(new Object()); } } private class AttributeListContentProvider extends ObservableListContentProvider { @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Override public Object[] getElements(Object inputElement) { return globalSecondaryIndex.getProjection().getNonKeyAttributes() != null ? globalSecondaryIndex.getProjection().getNonKeyAttributes().toArray() : new String[] {}; } } }
7,170
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/DynamoDBExplorerActionProvider.java
package com.amazonaws.eclipse.explorer.dynamodb; 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.IMenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.navigator.CommonActionProvider; import com.amazonaws.AmazonClientException; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.dynamodb.DynamoDBPlugin; import com.amazonaws.eclipse.dynamodb.testtool.StartTestToolWizard; import com.amazonaws.eclipse.dynamodb.testtool.TestToolManager; import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest; /** * Provides right-click context actions for items in the DynamoDB section of the * AWS resource explorer. */ public class DynamoDBExplorerActionProvider extends CommonActionProvider { @Override public void fillContextMenu(IMenuManager menu) { StructuredSelection selection = (StructuredSelection) getActionSite().getStructuredViewer().getSelection(); if ( selection.size() != 1 ) { return; } menu.add(new CreateTableAction()); if ( selection.getFirstElement() instanceof DynamoDBTableNode ) { String tableName = ((DynamoDBTableNode) selection.getFirstElement()).getTableName(); menu.add(new DeleteTableAction(tableName)); menu.add(new Separator()); menu.add(new TablePropertiesAction(tableName)); } else { if ("local".equals(RegionUtils.getCurrentRegion().getId())) { if (TestToolManager.INSTANCE.isRunning()) { menu.add(new StopTestToolAction()); } else if (TestToolManager.INSTANCE.isJava7Available()) { menu.add(new StartTestToolAction()); } } } } private static class StartTestToolAction extends Action { @Override public String getDescription() { return "Start the DynamoDB Local Test Tool"; } @Override public String getToolTipText() { return getDescription(); } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault() .getImageRegistry() .getDescriptor(AwsToolkitCore.IMAGE_DATABASE); } @Override public String getText() { return "Start DynamoDB Local"; } @Override public void run() { WizardDialog dialog = new WizardDialog( Display.getCurrent().getActiveShell(), new StartTestToolWizard() ); dialog.open(); if (null != DynamoDBContentProvider.getInstance()) { DynamoDBContentProvider.getInstance().refresh(); } } } private static class StopTestToolAction extends Action { @Override public String getDescription() { return "Stop the DynamoDB Local Test Tool"; } @Override public String getToolTipText() { return getDescription(); } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault() .getImageRegistry() .getDescriptor(AwsToolkitCore.IMAGE_DATABASE); } @Override public String getText() { return "Stop DynamoDB Local"; } @Override public void run() { TestToolManager.INSTANCE.stopVersion(); if (null != DynamoDBContentProvider.getInstance()) { DynamoDBContentProvider.getInstance().refresh(); } } } private static class CreateTableAction extends Action { @Override public String getDescription() { return "Create a new table"; } @Override public String getToolTipText() { return getDescription(); } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD); } @Override public String getText() { return "Create Table"; } @Override public void run() { WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new CreateTableWizard()); dialog.open(); if ( null != DynamoDBContentProvider.getInstance() ) { DynamoDBContentProvider.getInstance().refresh(); } } } private static class DeleteTableAction extends Action { private final String tableName; public DeleteTableAction(String tableName) { this.tableName = tableName; } @Override public String getDescription() { return "Delete table"; } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE); } @Override public String getToolTipText() { return getDescription(); } @Override public String getText() { return "Delete table"; } @Override public void run() { if ( new DeleteTableConfirmation().open() == 0 ) { final String accountId = AwsToolkitCore.getDefault().getCurrentAccountId(); new Job("Deleting table") { @Override protected IStatus run(IProgressMonitor monitor) { try { AwsToolkitCore.getClientFactory(accountId).getDynamoDBV2Client() .deleteTable(new DeleteTableRequest().withTableName(tableName)); } catch ( AmazonClientException e ) { return new Status(IStatus.ERROR, DynamoDBPlugin.PLUGIN_ID, "Failed to delete table", e); } if ( null != DynamoDBContentProvider.getInstance() ) { DynamoDBContentProvider.getInstance().refresh(); } return Status.OK_STATUS; } }.schedule(); } } } private static class TablePropertiesAction extends Action { private final String tableName; public TablePropertiesAction(String tableName) { this.tableName = tableName; } @Override public String getDescription() { return getText(); } @Override public String getToolTipText() { return getDescription(); } @Override public String getText() { return "Table Properties"; } @Override public void run() { final TablePropertiesDialog tablePropertiesDialog = new TablePropertiesDialog(tableName); if (tablePropertiesDialog.open() == 0) { final String accountId = AwsToolkitCore.getDefault().getCurrentAccountId(); new Job("Updating table " + tableName) { @Override protected IStatus run(IProgressMonitor monitor) { try { AwsToolkitCore.getClientFactory(accountId).getDynamoDBV2Client() .updateTable(tablePropertiesDialog.getUpdateRequest()); } catch ( AmazonClientException e ) { return new Status(IStatus.ERROR, DynamoDBPlugin.PLUGIN_ID, "Failed to update table", e); } return Status.OK_STATUS; } }.schedule(); } } } private static class DeleteTableConfirmation extends MessageDialog { public DeleteTableConfirmation() { super(Display.getCurrent().getActiveShell(), "Confirm table deletion", AwsToolkitCore.getDefault() .getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON), "Are you sure you want to delete this table?", MessageDialog.CONFIRM, new String[] { "OK", "Cancel" }, 0); } } }
7,171
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/TablePropertiesDialog.java
/* * Copyright 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.explorer.dynamodb; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnPixelData; 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.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndexDescription; import com.amazonaws.services.dynamodbv2.model.ProjectionType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.amazonaws.services.dynamodbv2.model.UpdateTableRequest; /** * Dialog to show the table properties. */ public class TablePropertiesDialog extends MessageDialog { private final String tableName; private final TableDescription tableDescription; private Text writeCapacityText; private Text readCapacityText; private Long readCapacity; private Long writeCapacity; protected TablePropertiesDialog(String tableName) { super(Display.getCurrent().getActiveShell(), "Table properties for " + tableName, AwsToolkitCore.getDefault().getImageRegistry() .get(AwsToolkitCore.IMAGE_AWS_ICON), null, MessageDialog.NONE, new String[] { "Update", "Cancel" }, 1); this.tableName = tableName; tableDescription = AwsToolkitCore.getClientFactory().getDynamoDBV2Client() .describeTable(new DescribeTableRequest().withTableName(tableName)).getTable(); readCapacity = tableDescription.getProvisionedThroughput().getReadCapacityUnits(); writeCapacity = tableDescription.getProvisionedThroughput().getWriteCapacityUnits(); setShellStyle(getShellStyle() | SWT.RESIZE); } public UpdateTableRequest getUpdateRequest() { return new UpdateTableRequest().withTableName(tableName).withProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(readCapacity).withWriteCapacityUnits(writeCapacity)); } @Override protected Control createCustomArea(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(comp); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(comp); newLabel(comp).setText("Created on:"); newReadOnlyTextField(comp).setText(tableDescription.getCreationDateTime().toString()); newLabel(comp).setText("Status:"); newReadOnlyTextField(comp).setText(tableDescription.getTableStatus()); newLabel(comp).setText("Item count:"); newReadOnlyTextField(comp).setText(tableDescription.getItemCount().toString()); newLabel(comp).setText("Size (bytes):"); newReadOnlyTextField(comp).setText(tableDescription.getTableSizeBytes().toString()); newLabel(comp).setText("Hash key attribute:"); newReadOnlyTextField(comp).setText(getHashKeyName()); newLabel(comp).setText("Hash key type:"); newReadOnlyTextField(comp).setText(getAttributeType(getHashKeyName())); if ( getRangeKeyName() != null ) { new Label(comp, SWT.READ_ONLY).setText("Range key attribute:"); newReadOnlyTextField(comp).setText(getRangeKeyName()); new Label(comp, SWT.READ_ONLY).setText("Range key type:"); newReadOnlyTextField(comp).setText(getAttributeType(getRangeKeyName())); } new Label(comp, SWT.READ_ONLY).setText("Read capacity units:"); readCapacityText = newTextField(comp); readCapacityText.setText(readCapacity.toString()); readCapacityText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { try { readCapacity = Long.parseLong(readCapacityText.getText()); } catch ( NumberFormatException e1 ) { readCapacity = null; } validate(); } }); new Label(comp, SWT.READ_ONLY).setText("Write capacity units:"); writeCapacityText = newTextField(comp); writeCapacityText.setText(writeCapacity.toString()); writeCapacityText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { try { writeCapacity = Long.parseLong(writeCapacityText.getText()); } catch ( NumberFormatException e1 ) { writeCapacity = null; } validate(); } }); if ( tableDescription.getProvisionedThroughput().getLastIncreaseDateTime() != null ) { new Label(comp, SWT.READ_ONLY).setText("Provisioned throughput last increased:"); newReadOnlyTextField(comp).setText( tableDescription.getProvisionedThroughput().getLastIncreaseDateTime().toString()); } if ( tableDescription.getProvisionedThroughput().getLastDecreaseDateTime() != null ) { new Label(comp, SWT.READ_ONLY).setText("Provisioned throughput last decreased:"); newReadOnlyTextField(comp).setText( tableDescription.getProvisionedThroughput().getLastDecreaseDateTime().toString()); } // Local secondary index Group group = new Group(comp, SWT.NONE); group.setText("Local Secondary Index"); group.setLayout(new GridLayout(1, false)); GridDataFactory.fillDefaults().grab(true, true).span(2, SWT.DEFAULT).applyTo(group); IndexTable table = new IndexTable(group); GridDataFactory.fillDefaults().grab(true, true).applyTo(table); table.refresh(); return comp; } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); validate(); } private Text newTextField(Composite comp) { Text text = new Text(comp, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(text); return text; } private Text newReadOnlyTextField(Composite comp) { Text text = new Text(comp, SWT.READ_ONLY); text.setBackground(comp.getBackground()); GridDataFactory.fillDefaults().grab(true, false).applyTo(text); return text; } private Label newLabel(Composite comp) { Label label = new Label(comp, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(label); return label; } private void validate() { if ( readCapacity == null || readCapacity < 5 ) { setErrorMessage("Please enter a read capacity of 5 or more."); return; } if ( writeCapacity == null || writeCapacity < 5 ) { setErrorMessage("Please enter a write capacity of 5 or more."); return; } setErrorMessage(null); } private void setErrorMessage(String message) { getButton(0).setEnabled(message == null); } private String getHashKeyName() { for (KeySchemaElement element : tableDescription.getKeySchema()) { if (element.getKeyType().equals(KeyType.HASH.toString())) { return element.getAttributeName(); } } return null; } private String getRangeKeyName() { for (KeySchemaElement element : tableDescription.getKeySchema()) { if (element.getKeyType().equals(KeyType.RANGE.toString())) { return element.getAttributeName(); } } return null; } private String getAttributeType(String attributeName) { for (AttributeDefinition definition : tableDescription.getAttributeDefinitions()) { if (definition.getAttributeName().equals(attributeName)) { return definition.getAttributeType(); } } return null; } // The table to show the local secondary index info private class IndexTable extends Composite { private TableViewer viewer; private IndexTableContentProvider contentProvider; private IndexTableLabelProvider labelProvider; IndexTable(Composite parent) { super(parent, SWT.NONE); TableColumnLayout tableColumnLayout = new TableColumnLayout(); this.setLayout(tableColumnLayout); contentProvider = new IndexTableContentProvider(); labelProvider = new IndexTableLabelProvider(); 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()); } // Enforce call getElement method in contentProvider public void refresh() { viewer.setInput(new Object()); } protected final class IndexTableContentProvider extends ArrayContentProvider { @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Override public Object[] getElements(Object inputElement) { if (tableDescription == null || tableDescription.getLocalSecondaryIndexes() == null) { return new LocalSecondaryIndexDescription[0]; } return tableDescription.getLocalSecondaryIndexes().toArray(); } } protected final class IndexTableLabelProvider 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 LocalSecondaryIndexDescription == false) return ""; LocalSecondaryIndexDescription index = (LocalSecondaryIndexDescription) element; switch (columnIndex) { case 0: return index.getIndexName(); case 1: String returnString = ""; returnString += index.getKeySchema().get(1).getAttributeName() + " ("; returnString += getAttributeType(index.getKeySchema().get(1).getAttributeName()) + ")"; return returnString; case 2: return index.getIndexSizeBytes().toString(); case 3: return index.getItemCount().toString(); case 4: return getProjectionAttributes(index); } return element.toString(); } } // Generate a String has the detail info about projection in this LSI private String getProjectionAttributes(LocalSecondaryIndexDescription index) { String returnString = ""; if (index.getProjection().getProjectionType().equals(ProjectionType.ALL.toString())) { return index.getProjection().getProjectionType(); } else if (index.getProjection().getProjectionType().equals(ProjectionType.INCLUDE.toString())) { for (String attribute : index.getProjection().getNonKeyAttributes()) { returnString += attribute + ", "; } returnString = returnString.substring(0, returnString.length() - 2); return returnString; } else { returnString += getHashKeyName() + ", "; if (getRangeKeyName() != null) { returnString += getRangeKeyName() + ", "; } returnString += index.getKeySchema().get(1).getAttributeName(); return returnString; } } private void createColumns(TableColumnLayout columnLayout, Table table) { createColumn(table, columnLayout, "Index Name"); createColumn(table, columnLayout, "Attribute To Index"); createColumn(table, columnLayout, "Index Size (Bytes)"); createColumn(table, columnLayout, "Item Count"); createColumn(table, columnLayout, "Projected Attributes"); } 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 ColumnPixelData(150)); return column; } } }
7,172
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/CreateTableSecondPage.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.dynamodb; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; 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.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnPixelData; 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.jface.wizard.WizardPage; 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.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.Projection; public class CreateTableSecondPage extends WizardPage { private final List<LocalSecondaryIndex> localSecondaryIndexes; private final List<AttributeDefinition> localSecondaryIndexKeyAttributes; private IndexTable<LocalSecondaryIndex> localSecondaryIndexesTable; private final int MAX_NUM_LSI = 5; private final List<GlobalSecondaryIndex> globalSecondaryIndexes; private final List<List<AttributeDefinition>> globalSecondaryIndexKeyAttributes; private IndexTable<GlobalSecondaryIndex> globalSecondaryIndexesTable; private final int MAX_NUM_GSI = 5; private CreateTableWizard wizard; private final String OK_MESSAGE = "Add one or more Local/Global Secondary Indexes(optional)"; CreateTableSecondPage(CreateTableWizard wizard) { super("Configure table"); setMessage(OK_MESSAGE); setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO)); localSecondaryIndexes = new LinkedList<>(); wizard.getDataModel().setLocalSecondaryIndexes(localSecondaryIndexes); localSecondaryIndexKeyAttributes = new LinkedList<>(); globalSecondaryIndexes = new LinkedList<>(); wizard.getDataModel().setGlobalSecondaryIndexes(globalSecondaryIndexes); globalSecondaryIndexKeyAttributes = new LinkedList<>(); this.wizard = wizard; } @Override public void createControl(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(comp); GridLayoutFactory.fillDefaults().numColumns(1).applyTo(comp); createLinkSection(comp); // LSI Group lsiGroup = CreateTablePageUtil.newGroup(comp, "Local Secondary Index", 1); GridDataFactory.fillDefaults().grab(true, true).applyTo(lsiGroup); Button addLSIButton = new Button(lsiGroup, SWT.PUSH); addLSIButton.setText("Add Local Secondary Index"); addLSIButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD)); addLSIButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (localSecondaryIndexes.size() >= MAX_NUM_LSI) { new MessageDialog(getShell(), "Validation Error", null, "A table cannot have more than five local secondary indexes.", MessageDialog.ERROR, new String[] { "OK", "CANCEL" }, 0).open(); return; } AddLSIDialog addLSIDialog = new AddLSIDialog(Display.getCurrent().getActiveShell(), wizard.getDataModel()); if (addLSIDialog.open() == 0) { // Add the LSI schema object localSecondaryIndexes.add(addLSIDialog.getLocalSecondaryIndex()); // Add the key attribute definitions associated with this LSI localSecondaryIndexKeyAttributes.add(addLSIDialog.getIndexRangeKeyAttributeDefinition()); wizard.collectAllAttribtueDefinitions(); localSecondaryIndexesTable.refresh(); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); // LSI label provider IndexTable.IndexTableLabelProvider localSecondaryIndexTableLabelProvider = new IndexTable.IndexTableLabelProvider() { @Override public String getColumnText(Object element, int columnIndex) { if (element instanceof LocalSecondaryIndex == false) return ""; LocalSecondaryIndex index = (LocalSecondaryIndex) element; switch (columnIndex) { case 0: // index name return index.getIndexName(); case 1: // index range key String returnString = ""; returnString += index.getKeySchema().get(1).getAttributeName() + " ("; returnString += findAttributeType(index.getKeySchema().get(1).getAttributeName()) + ")"; return returnString; case 2: // index projection return IndexTable.getProjectionAttributes( index.getProjection(), index.getKeySchema(), wizard.getDataModel()); } return element.toString(); } }; localSecondaryIndexesTable = new IndexTable<LocalSecondaryIndex>( lsiGroup, localSecondaryIndexes, localSecondaryIndexTableLabelProvider) { @Override protected void createColumns(TableColumnLayout columnLayout, Table table) { createColumn(table, columnLayout, "Index Name"); createColumn(table, columnLayout, "Attribute To Index"); createColumn(table, columnLayout, "Projected Attributes"); } @Override protected void onRemoveItem(int removed) { localSecondaryIndexKeyAttributes.remove(removed); wizard.collectAllAttribtueDefinitions(); } }; GridDataFactory.fillDefaults().grab(true, true).applyTo(localSecondaryIndexesTable); // GSI Group gsiGroup = CreateTablePageUtil.newGroup(comp, "Global Secondary Index", 1); GridDataFactory.fillDefaults().grab(true, true).applyTo(gsiGroup); Button addGSIButton = new Button(gsiGroup, SWT.PUSH); addGSIButton.setText("Add Global Secondary Index"); addGSIButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD)); addGSIButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (globalSecondaryIndexes.size() >= MAX_NUM_GSI) { new MessageDialog(getShell(), "Validation Error", null, "A table cannot have more than five global secondary indexes.", MessageDialog.ERROR, new String[] { "OK", "CANCEL" }, 0).open(); return; } AddGSIDialog addGSIDialog = new AddGSIDialog(Display.getCurrent().getActiveShell(), wizard.getDataModel()); if (addGSIDialog.open() == 0) { globalSecondaryIndexes.add(addGSIDialog.getGlobalSecondaryIndex()); globalSecondaryIndexKeyAttributes.add(addGSIDialog.getIndexKeyAttributeDefinitions()); wizard.collectAllAttribtueDefinitions(); globalSecondaryIndexesTable.refresh(); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); // GSI label provider IndexTable.IndexTableLabelProvider globalSecondaryIndexTableLabelProvider = new IndexTable.IndexTableLabelProvider() { @Override public String getColumnText(Object element, int columnIndex) { if (element instanceof GlobalSecondaryIndex == false) return ""; GlobalSecondaryIndex index = (GlobalSecondaryIndex) element; switch (columnIndex) { case 0: // index name return index.getIndexName(); case 1: // index hash String returnString = ""; returnString += index.getKeySchema().get(0).getAttributeName() + " ("; returnString += findAttributeType(index.getKeySchema().get(0).getAttributeName()) + ")"; return returnString; case 2: // index range returnString = ""; if (index.getKeySchema().size() > 1) { returnString += index.getKeySchema().get(1).getAttributeName() + " ("; returnString += findAttributeType(index.getKeySchema().get(1).getAttributeName()) + ")"; } return returnString; case 3: // index projection return IndexTable.getProjectionAttributes( index.getProjection(), index.getKeySchema(), wizard.getDataModel()); case 4: // index throughput return "Read : " + index.getProvisionedThroughput().getReadCapacityUnits() + ", Write : " + index.getProvisionedThroughput().getWriteCapacityUnits(); default: return ""; } } }; globalSecondaryIndexesTable = new IndexTable<GlobalSecondaryIndex>( gsiGroup, globalSecondaryIndexes, globalSecondaryIndexTableLabelProvider) { @Override protected void createColumns(TableColumnLayout columnLayout, Table table) { createColumn(table, columnLayout, "Index Name"); createColumn(table, columnLayout, "Index Hash Key"); createColumn(table, columnLayout, "Index Range Key"); createColumn(table, columnLayout, "Projected Attributes"); createColumn(table, columnLayout, "Provisioned Throughput"); } @Override protected void onRemoveItem(int removed) { globalSecondaryIndexKeyAttributes.remove(removed); wizard.collectAllAttribtueDefinitions(); } }; GridDataFactory.fillDefaults().grab(true, true).applyTo(globalSecondaryIndexesTable); setControl(comp); } public void createLinkSection(Composite parent) { String ConceptUrl1 = "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSI.html"; String ConceptUrl2 = "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html"; Link link = new Link(parent, SWT.NONE | SWT.WRAP); link.setText("You can only define local/global secondary indexes at table creation time, and cannot remove them or modify the index key schema later. " + "Local/global secondary indexes are not appropriate for every application; see " + "<a href=\"" + ConceptUrl1 + "\">Local Secondary Indexes</a> and <a href=\"" + ConceptUrl2 + "\">Global Secondary Indexes</a>.\n"); link.addListener(SWT.Selection, new WebLinkListener()); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.widthHint = 200; link.setLayoutData(gridData); } public Set<AttributeDefinition> getAllIndexKeyAttributeDefinitions() { Set<AttributeDefinition> allAttrs = new HashSet<>(); for (AttributeDefinition lsiKey : localSecondaryIndexKeyAttributes) { allAttrs.add(lsiKey); } for (List<AttributeDefinition> gsiKey : globalSecondaryIndexKeyAttributes) { allAttrs.addAll(gsiKey); } return allAttrs; } private String findAttributeType(String attributeName) { for (AttributeDefinition attribute : wizard.getDataModel().getAttributeDefinitions()) { if (attribute.getAttributeName().equals(attributeName)) { return attribute.getAttributeType(); } } return ""; } /** Abstract base class that could be customized for LSI/GSI */ private static abstract class IndexTable <T> extends Composite { private final List<T> indexes; private final TableViewer viewer; IndexTable(Composite parent, final List<T> indexes, final IndexTableLabelProvider labelProvider) { super(parent, SWT.NONE); this.indexes = indexes; TableColumnLayout tableColumnLayout = new TableColumnLayout(); this.setLayout(tableColumnLayout); 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(new IndexTableContentProvider()); 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() { int selected = viewer.getTable().getSelectionIndex(); IndexTable.this.indexes.remove(selected); IndexTable.this.onRemoveItem(selected); refresh(); } @Override public String getText() { return "Delete Index"; } }); } } }); viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable())); } protected abstract void createColumns(TableColumnLayout columnLayout, Table table); /** * Callback for any additional operations to be executed after an item * in the table is removed. */ protected abstract void onRemoveItem(int removed); protected 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 ColumnPixelData(150)); return column; } protected static abstract class IndexTableLabelProvider 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 abstract String getColumnText(Object element, int columnIndex); } /** Shared by LSI and GSI table */ private final class IndexTableContentProvider extends ArrayContentProvider { @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Override public Object[] getElements(Object inputElement) { return indexes.toArray(); } } /** Enforce call getElement method in contentProvider */ private void refresh() { viewer.setInput(new Object()); } /** Generate a String has the detail info about the project attribute. */ private static String getProjectionAttributes(Projection indexProjection, List<KeySchemaElement> indexKeys, CreateTableDataModel dataModel) { String returnString = ""; String DELIM = ", "; if (indexProjection.getProjectionType().equals("All Attributes")) { return indexProjection.getProjectionType(); } else if (indexProjection.getProjectionType().equals("Specify Attributes")) { return CreateTablePageUtil.stringJoin(indexProjection.getNonKeyAttributes(), DELIM); } else { // Primary keys Set<String> projectedKeys = new HashSet<>(); returnString += dataModel.getHashKeyName() + DELIM; projectedKeys.add(dataModel.getHashKeyName()); if (dataModel.getEnableRangeKey()) { returnString += dataModel.getRangeKeyName() + DELIM; projectedKeys.add(dataModel.getRangeKeyName()); } // Index keys (we should not include index keys that are already part of the primary key) for (KeySchemaElement indexKey : indexKeys) { String indexKeyName = indexKey.getAttributeName(); if ( !projectedKeys.contains(indexKeyName) ) { returnString += indexKeyName + DELIM; projectedKeys.add(indexKeyName); } } return returnString.substring(0, returnString.length() - DELIM.length()); } } } }
7,173
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/AddLSIDialog.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.dynamodb; import java.util.Arrays; import java.util.LinkedList; 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.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.databinding.viewers.ObservableListContentProvider; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.NotEmptyValidator; import com.amazonaws.eclipse.dynamodb.AbstractAddNewAttributeDialog; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.Projection; public class AddLSIDialog extends TitleAreaDialog { /** Widget used as data-binding targets **/ private Text attributeNameText; private Text indexNameText; private Combo attributeTypeCombo; private Combo projectionTypeCombo; private Button addAttributeButton; private Button okButton; /** The data objects that will be used to generate the service request **/ private final LocalSecondaryIndex localSecondaryIndex; private final AttributeDefinition indexRangeKeyAttributeDefinition; private final DataBindingContext bindingContext = new DataBindingContext(); /** The model value objects for data-binding **/ private final IObservableValue indexNameModel; private final IObservableValue indexRangeKeyNameInKeySchemaDefinitionModel; private final IObservableValue indexRangeKeyNameInAttributeDefinitionsModel; private final IObservableValue indexRangeKeyAttributeTypeModel; private final IObservableValue projectionTypeModel; private final String primaryRangeKeyName; private final int primaryRangeKeyTypeComboIndex; private static final String[] DATA_TYPE_STRINGS = new String[] { "String", "Number", "Binary" }; private static final String[] PROJECTED_ATTRIBUTES = new String[] { "All Attributes", "Table and Index Keys", "Specify Attributes" }; public AddLSIDialog(Shell parentShell, CreateTableDataModel dataModel) { super(parentShell); // Initialize the variable necessary for data-binding localSecondaryIndex = new LocalSecondaryIndex(); // The index range key to be defined by the user KeySchemaElement rangeKeySchemaDefinition = new KeySchemaElement() .withAttributeName(null) .withKeyType(KeyType.RANGE); localSecondaryIndex.withKeySchema( new KeySchemaElement() .withAttributeName(dataModel.getHashKeyName()) .withKeyType(KeyType.HASH), rangeKeySchemaDefinition); localSecondaryIndex.setProjection(new Projection()); // The attribute definition for the index range key indexRangeKeyAttributeDefinition = new AttributeDefinition(); // Initialize IObservableValue objects that keep track of data variables indexNameModel = PojoObservables.observeValue(localSecondaryIndex, "indexName"); indexRangeKeyNameInKeySchemaDefinitionModel = PojoObservables.observeValue(rangeKeySchemaDefinition, "attributeName"); indexRangeKeyAttributeTypeModel = PojoObservables.observeValue(indexRangeKeyAttributeDefinition, "attributeType"); indexRangeKeyNameInAttributeDefinitionsModel = PojoObservables.observeValue(indexRangeKeyAttributeDefinition, "attributeName"); projectionTypeModel = PojoObservables.observeValue(localSecondaryIndex.getProjection(), "projectionType"); // Get the information of the primary range key if (dataModel.getEnableRangeKey()) { primaryRangeKeyName = dataModel.getRangeKeyName(); primaryRangeKeyTypeComboIndex = Arrays.<String>asList(DATA_TYPE_STRINGS).indexOf(dataModel.getRangeKeyType()); } else { primaryRangeKeyName = null; primaryRangeKeyTypeComboIndex = -1; } setShellStyle(SWT.RESIZE); } @Override protected Control createContents(Composite parent) { Control contents = super.createContents(parent); setTitle("Add Local Secondary Index"); setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO)); okButton = getButton(IDialogConstants.OK_ID); okButton.setEnabled(false); return contents; } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText("Add Local Secondary Index"); shell.setMinimumSize(400, 500); } @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(2, false)); // Index range key attribute name new Label(composite, SWT.NONE | SWT.READ_ONLY).setText("Attribute to Index:"); attributeNameText = new Text(composite, SWT.BORDER); bindingContext.bindValue(SWTObservables.observeText(attributeNameText, SWT.Modify), indexRangeKeyNameInKeySchemaDefinitionModel); ChainValidator<String> attributeNameValidationStatusProvider = new ChainValidator<>(indexRangeKeyNameInKeySchemaDefinitionModel, new NotEmptyValidator("Please provide an attribute name")); bindingContext.addValidationStatusProvider(attributeNameValidationStatusProvider); bindingContext.bindValue(SWTObservables.observeText(attributeNameText, SWT.Modify), indexRangeKeyNameInAttributeDefinitionsModel); attributeNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (attributeNameText.getText().equals(primaryRangeKeyName) && attributeTypeCombo != null && primaryRangeKeyTypeComboIndex > -1) { attributeTypeCombo.select(primaryRangeKeyTypeComboIndex); attributeTypeCombo.setEnabled(false); } else if (attributeTypeCombo != null) { attributeTypeCombo.setEnabled(true); } } }); GridDataFactory.fillDefaults().grab(true, false).applyTo(attributeNameText); // Index range key attribute type new Label(composite, SWT.NONE | SWT.READ_ONLY).setText("Attribute Type:"); attributeTypeCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY); attributeTypeCombo.setItems(DATA_TYPE_STRINGS); attributeTypeCombo.select(0); bindingContext.bindValue(SWTObservables.observeSelection(attributeTypeCombo), indexRangeKeyAttributeTypeModel); // Index name new Label(composite, SWT.NONE | SWT.READ_ONLY).setText("Index Name:"); indexNameText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(indexNameText); bindingContext.bindValue(SWTObservables.observeText(indexNameText, SWT.Modify), indexNameModel); ChainValidator<String> indexNameValidationStatusProvider = new ChainValidator<>(indexNameModel, new NotEmptyValidator("Please provide an index name")); bindingContext.addValidationStatusProvider(indexNameValidationStatusProvider); // Projection type new Label(composite, SWT.NONE | SWT.READ_ONLY).setText("Projected Attributes:"); projectionTypeCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY); projectionTypeCombo.setItems(PROJECTED_ATTRIBUTES); projectionTypeCombo.select(0); bindingContext.bindValue(SWTObservables.observeSelection(projectionTypeCombo), projectionTypeModel); projectionTypeCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (projectionTypeCombo.getSelectionIndex() == 2) { // Enable the list for adding non-key attributes to the projection addAttributeButton.setEnabled(true); } else { addAttributeButton.setEnabled(false); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); // Non-key attributes in the projection final AttributeList attributeList = new AttributeList(composite); GridDataFactory.fillDefaults().grab(true, true).hint(SWT.DEFAULT, SWT.DEFAULT).applyTo(attributeList); addAttributeButton = new Button(composite, SWT.PUSH); addAttributeButton.setText("Add Attribute"); addAttributeButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); addAttributeButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD)); addAttributeButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { AddNewAttributeDialog newAttributeTable = new AddNewAttributeDialog(); if (newAttributeTable.open() == 0) { // lazy-initialize the list if (null == localSecondaryIndex.getProjection().getNonKeyAttributes()) { localSecondaryIndex.getProjection().setNonKeyAttributes(new LinkedList<String>()); } localSecondaryIndex.getProjection().getNonKeyAttributes().add(newAttributeTable.getNewAttributeName()); attributeList.refresh(); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); addAttributeButton.setEnabled(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.getSeverity() == Status.ERROR) { setErrorMessage(status.getMessage()); if (okButton != null) { okButton.setEnabled(false); } } else { setErrorMessage(null); if (okButton != null) { okButton.setEnabled(true); } } } }); bindingContext.updateModels(); return composite; } public LocalSecondaryIndex getLocalSecondaryIndex() { return localSecondaryIndex; } /** * Get the AttributeDefinition of the index range key as specified in this dialog. */ public AttributeDefinition getIndexRangeKeyAttributeDefinition() { return indexRangeKeyAttributeDefinition; } private class AddNewAttributeDialog extends AbstractAddNewAttributeDialog { @Override public void validate() { if (getButton(0) == null) return; if (getNewAttributeName().length() == 0) { getButton(0).setEnabled(false); return; } getButton(0).setEnabled(true); return; } } /** The list widget for adding projected non-key attributes. **/ private class AttributeList extends Composite { private ListViewer viewer; private AttributeListContentProvider attributeListContentProvider; public AttributeList(Composite parent) { super(parent, SWT.NONE); this.setLayout(new GridLayout()); viewer = new ListViewer(this, SWT.BORDER | SWT.V_SCROLL | SWT.READ_ONLY); attributeListContentProvider = new AttributeListContentProvider(); viewer.setContentProvider(attributeListContentProvider); viewer.setLabelProvider(new LabelProvider()); GridDataFactory.fillDefaults().grab(true, true).applyTo(viewer.getList()); viewer.getList().setVisible(true); MenuManager menuManager = new MenuManager("#PopupMenu"); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { if (viewer.getList().getSelectionCount() > 0) { manager.add(new Action() { @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE); } @Override public void run() { // In theory, this should never be null. if (null != localSecondaryIndex.getProjection().getNonKeyAttributes()) { localSecondaryIndex.getProjection().getNonKeyAttributes().remove(viewer.getList().getSelectionIndex()); } refresh(); } @Override public String getText() { return "Delete Attribute"; } }); } } }); viewer.getList().setMenu(menuManager.createContextMenu(viewer.getList())); } // Enforce to call getElements to update list public void refresh() { viewer.setInput(new Object()); } } private class AttributeListContentProvider extends ObservableListContentProvider { @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Override public Object[] getElements(Object inputElement) { return localSecondaryIndex.getProjection().getNonKeyAttributes() != null ? localSecondaryIndex.getProjection().getNonKeyAttributes().toArray() : new String[] {}; } } }
7,174
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/test/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/test/com/amazonaws/eclipse/ec2/InstanceTypesParserTest.java
package com.amazonaws.eclipse.ec2; import static org.junit.Assert.*; import java.io.InputStream; import java.util.List; import org.junit.Test; public class InstanceTypesParserTest { /** * Tests the InstanceType parser by loading the fallback instance type * descriptions and making sure the loaded instance types look correct. * * This test requires the etc directory to be on the build-path in order for * the fallback file to be loaded. */ @Test public void testInstanceTypesParser() throws Exception { InputStream inputStream = getClass().getClassLoader().getResourceAsStream("InstanceTypes.xml"); assertNotNull(inputStream); InstanceTypesParser parser = new InstanceTypesParser(inputStream); assertEquals("m1.small", parser.parseDefaultInstanceTypeId()); List<InstanceType> instanceTypes = parser.parseInstanceTypes(); assertTrue(instanceTypes.size() > 5); for (InstanceType type : instanceTypes) { assertNotNull(type.id); assertNotNull(type.diskSpaceWithUnits); assertNotNull(type.memoryWithUnits); assertNotNull(type.architectureBits); assertNotNull(type.name); assertTrue(type.numberOfVirtualCores > 0); } } }
7,175
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/test/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/test/com/amazonaws/eclipse/ec2/AmiToolsVersionTest.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Unit tests for the AmiToolsVersion class. */ public class AmiToolsVersionTest { /** * Tests that known version numbers are parsed correctly. */ @Test public void testParsing() throws Exception { AmiToolsVersion version = new AmiToolsVersion("1.3-123456"); assertEquals(1, version.getMajorVersion()); assertEquals(3, version.getMinorVersion()); assertEquals(123456, version.getPatch()); version = new AmiToolsVersion("1.3-20041 20071010\n"); assertEquals(1, version.getMajorVersion()); assertEquals(3, version.getMinorVersion()); assertEquals(20041, version.getPatch()); } /** * Tests that a version number with non-numeric components will correctly * cause a ParseException to be thrown. */ @Test(expected = java.text.ParseException.class) public void testParseExceptionNonNumeric() throws Exception { new AmiToolsVersion("1.X-12345"); } /** * Tests that a version number in the wrong format will correctly cause a * ParseException to be thrown. */ @Test(expected = java.text.ParseException.class) public void testParseExceptionWrongFormat() throws Exception { new AmiToolsVersion("1.2.3.45"); } /** * Tests that the isGreaterThan method correctly compares versions with each * other. */ @Test public void testIsGreaterThan() throws Exception { AmiToolsVersion a = new AmiToolsVersion("1.0-99999999"); AmiToolsVersion b = new AmiToolsVersion("1.3-99999999"); AmiToolsVersion c = new AmiToolsVersion("2.0-1"); assertTrue(c.isGreaterThan(b)); assertTrue(b.isGreaterThan(a)); assertFalse(a.isGreaterThan(b)); assertFalse(b.isGreaterThan(c)); } }
7,176
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer/ec2/EC2ContentProvider.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.ec2; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.explorer.AWSResourcesRootElement; import com.amazonaws.eclipse.explorer.AbstractContentProvider; public class EC2ContentProvider extends AbstractContentProvider { @Override public boolean hasChildren(Object element) { return (element instanceof AWSResourcesRootElement || element instanceof EC2RootElement); } @Override public Object[] loadChildren(Object parentElement) { if ( parentElement instanceof AWSResourcesRootElement ) { return new Object[] { EC2RootElement.ROOT_ELEMENT }; } if ( parentElement instanceof EC2RootElement ) { return new Object[] { EC2ExplorerNodes.AMIS_NODE, EC2ExplorerNodes.INSTANCES_NODE, EC2ExplorerNodes.EBS_NODE, EC2ExplorerNodes.SECURITY_GROUPS_NODE}; } return null; } @Override public String getServiceAbbreviation() { return ServiceAbbreviations.EC2; } }
7,177
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer/ec2/EC2RootElement.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.ec2; import org.eclipse.core.runtime.PlatformObject; /** Root element for EC2 in the AWS resource browser. */ public class EC2RootElement extends PlatformObject { public static final EC2RootElement ROOT_ELEMENT = new EC2RootElement(); }
7,178
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer/ec2/ExplorerSorter.java
package com.amazonaws.eclipse.explorer.ec2; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import com.amazonaws.eclipse.explorer.ExplorerNode; public class ExplorerSorter extends ViewerSorter { @Override public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof ExplorerNode && e2 instanceof ExplorerNode) { ExplorerNode nn1 = (ExplorerNode)e1; ExplorerNode nn2 = (ExplorerNode)e2; Integer sortPriority1 = nn1.getSortPriority(); Integer sortPriority2 = nn2.getSortPriority(); return sortPriority1.compareTo(sortPriority2); } else return super.compare(viewer, e1, e2); } }
7,179
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer/ec2/EC2ExplorerNodes.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.ec2; import org.eclipse.jface.action.Action; import org.eclipse.swt.graphics.Image; import static com.amazonaws.eclipse.ec2.Ec2PluginConstants.AMIS_VIEW_ID; import static com.amazonaws.eclipse.ec2.Ec2PluginConstants.INSTANCES_VIEW_ID; import static com.amazonaws.eclipse.ec2.Ec2PluginConstants.EBS_VIEW_ID; import static com.amazonaws.eclipse.ec2.Ec2PluginConstants.SECURITY_GROUPS_VIEW_ID; import com.amazonaws.eclipse.ec2.Ec2Plugin; import com.amazonaws.eclipse.explorer.ExplorerNode; class EC2ExplorerNodes { public static final ExplorerNode AMIS_NODE = new ExplorerNode("Amazon Machine Images (AMIs)", 1, loadImage("ami"), newOpenViewAction("Open EC2 AMIs View", AMIS_VIEW_ID)); public static final ExplorerNode INSTANCES_NODE = new ExplorerNode("Instances", 2, loadImage("server"), newOpenViewAction("Open EC2 Instances View", INSTANCES_VIEW_ID)); public static final ExplorerNode EBS_NODE = new ExplorerNode("Elastic Block Storage (EBS)", 3, loadImage("volume"), newOpenViewAction("Open EC2 Elastic Block Storage View", EBS_VIEW_ID)); public static final ExplorerNode SECURITY_GROUPS_NODE = new ExplorerNode("Security Groups", 4, loadImage("shield"), newOpenViewAction("Open EC2 Security Groups View", SECURITY_GROUPS_VIEW_ID)); private static Image loadImage(String imageId) { return Ec2Plugin.getDefault().getImageRegistry().get(imageId); } private static Action newOpenViewAction(String title, String viewId) { OpenViewAction action = new OpenViewAction(viewId); action.setText(title); return action; } }
7,180
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer/ec2/EC2LabelProvider.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.ec2; import org.eclipse.swt.graphics.Image; import com.amazonaws.eclipse.ec2.Ec2Plugin; import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider; public class EC2LabelProvider extends ExplorerNodeLabelProvider { @Override public String getText(Object element) { if (element instanceof EC2RootElement) return "Amazon EC2"; return getExplorerNodeText(element); } @Override public Image getDefaultImage(Object element) { if ( element instanceof EC2RootElement ) { return Ec2Plugin.getDefault().getImageRegistry().get("ec2-service"); } return null; } }
7,181
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/explorer/ec2/OpenViewAction.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.ec2; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.statushandlers.StatusManager; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.ec2.Ec2Plugin; import com.amazonaws.eclipse.explorer.AwsAction; import static com.amazonaws.eclipse.ec2.Ec2PluginConstants.AMIS_VIEW_ID; import static com.amazonaws.eclipse.ec2.Ec2PluginConstants.INSTANCES_VIEW_ID; import static com.amazonaws.eclipse.ec2.Ec2PluginConstants.EBS_VIEW_ID; import static com.amazonaws.eclipse.ec2.Ec2PluginConstants.SECURITY_GROUPS_VIEW_ID; public class OpenViewAction extends AwsAction { private final String viewId; public OpenViewAction(String viewId) { super(mapToMetricType(viewId)); this.viewId = viewId; } @Override public void doRun() { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(viewId); actionSucceeded(); } catch (PartInitException e) { actionFailed(); IStatus status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID, "Unable to open view " + viewId, e); StatusManager.getManager().handle(status, StatusManager.LOG); } finally { actionFinished(); } } private static AwsToolkitMetricType mapToMetricType(String viewId) { switch(viewId) { case AMIS_VIEW_ID: return AwsToolkitMetricType.EXPLORER_EC2_OPEN_AMIS_VIEW; case INSTANCES_VIEW_ID: return AwsToolkitMetricType.EXPLORER_EC2_OPEN_INSTANCES_VIEW; case EBS_VIEW_ID: return AwsToolkitMetricType.EXPLORER_EC2_OPEN_EBS_VIEW; case SECURITY_GROUPS_VIEW_ID: return AwsToolkitMetricType.EXPLORER_EC2_OPEN_SECURITY_GROUPS_VIEW; } return AwsToolkitMetricType.EXPLORER_EC2_OPEN_VIEW; } }
7,182
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/Ec2InstanceLauncher.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import com.amazonaws.AmazonClientException; import com.amazonaws.eclipse.core.AWSClientFactory; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.IamInstanceProfileSpecification; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Placement; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; /** * Responsible for launching EC2 instances and watching them to see if they * come up correctly. The big value of this class is that it handles monitoring * the launched instances to see if they started correctly or if they failed. */ public class Ec2InstanceLauncher { /** Factory providing EC2 clients */ private final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(); /** The name of the key pair to launch instances with */ private String keyPairName; /** The name of the security group to launch instances with */ private String securityGroupName; /** The number of instances to launch */ private int numberOfInstances; /** The user data to pass to the launched instances */ private String userData; /** The name of the zone to bring up instances in */ private String availabilityZoneName; /** The id of the AMI to launch instances with */ private String imageId; /** The type of instances to launch */ private String instanceType; /** The endpoint of the EC2 region in which instances should be launched */ private String regionEndpoint; /** The arn of the instance profile to launch with */ private String instanceProfileArn; /** * Optional progress monitor so that this launcher can poll to see if the * user has canceled the launch request. */ private IProgressMonitor progressMonitor; /** Shared logger */ private static final Logger logger = Logger.getLogger(Ec2InstanceLauncher.class.getName()); /** * Constructs a new EC2 instance launcher, ready to launch the specified * image with the specified key pair. Additional, optional launch parameters * can be configured by calling the setters. * * @param imageId * The id of the image to launch. * @param keyPairName * The name of the key pair with which to launch instances. */ public Ec2InstanceLauncher(String imageId, String keyPairName) { this.imageId = imageId; this.keyPairName = keyPairName; this.numberOfInstances = 1; this.instanceType = InstanceTypes.getDefaultInstanceType().id; } /* * Setters */ /** * Sets the EC2 region endpoint that should be used when launching these * instances. * * @param regionEndpoint * The EC2 region endpoint that should be used when launching * these instances. */ public void setEc2RegionEndpoint(String regionEndpoint) { this.regionEndpoint = regionEndpoint; } /** * Sets the security group with which this launcher will launch instances. * * @param securityGroupName * The name of the security group with which to launch instances. */ public void setSecurityGroup(String securityGroupName) { this.securityGroupName = securityGroupName; } /** * Sets the number of instances this launcher will launch. * * @param numberOfInstances * The number of instances to be launched. */ public void setNumberOfInstances(int numberOfInstances) { this.numberOfInstances = numberOfInstances; } /** * Sets the user data with which this launcher will launch instances. * * @param userData * The user data to launch instances with. */ public void setUserData(String userData) { this.userData = userData; } /** * Sets the isntance profile arn to launch with. */ public void setInstanceProfileArn(String instanceProfileArn) { this.instanceProfileArn = instanceProfileArn; } /** * Sets the availability zone in which to launch instances. * * @param availabilityZoneName * The availability zone in which to launch instances. */ public void setAvailabilityZone(String availabilityZoneName) { this.availabilityZoneName = availabilityZoneName; } /** * The String ID representing the type of instances to launch. * * @param instanceType * The instance type ID representing the type of instances to * launch. */ public void setInstanceType(String instanceType) { this.instanceType = instanceType; } /** * Sets the optional progress monitor to use to check to see if the user has * canceled this launch. * * @param progressMonitor * The progress monitor to use when checking to see if the user * has canceled this launch. */ public void setProgressMonitor(IProgressMonitor progressMonitor) { this.progressMonitor = progressMonitor; } /* * Launch methods */ /** * Launches EC2 instances with the parameters configured in this launcher * and waits for them to all come online before returning. * * @throws AmazonClientException * If any problems prevented the instances from starting up. * @throws OperationCanceledException * If the user canceled the request for which these instances * were being launched. */ public List<Instance> launchAndWait() throws AmazonClientException, OperationCanceledException { return startInstances(true); } /** * Launches EC2 instances with the parameters configured in this launcher * and returns immediately, without waiting for the new instances to come * up. * * @throws AmazonClientException * If any problems prevented the instances from starting up. */ public void launch() throws AmazonClientException { startInstances(false); } /* * Private Interface */ /** * Returns an AWS EC2 client ready to be used. If the caller specified an * EC2 region endpoint, this client will be fully configured to talk to that * region, otherwise it will be configured to work with the default region. * * @return An AWS EC2 client ready to be used. */ private AmazonEC2 getEc2Client() { if (regionEndpoint != null) { return clientFactory.getEC2ClientByEndpoint(regionEndpoint); } return Ec2Plugin.getDefault().getDefaultEC2Client(); } /** * Starts up instances and optionally waits for them to come online. * * @param waitForInstances * True if the caller wants this method to block until the * instances are online, in which case a List of instances will * be returned, otherwise this method will request that the * instances be launched and immediately return. * * @throws AmazonClientException * If any problems were encountered communicating with Amazon * EC2. * @throws OperationCanceledException * If the user canceled the request for which these instances * were being launched. */ private List<Instance> startInstances(boolean waitForInstances) throws AmazonClientException, OperationCanceledException { logger.info("Requested to start " + numberOfInstances + " new instances."); AmazonEC2 ec2 = getEc2Client(); List<String> securityGroupList = null; if (this.securityGroupName != null) { securityGroupList = Arrays.asList(new String[] {securityGroupName}); } RunInstancesRequest request = new RunInstancesRequest(); request.setImageId(imageId); request.setSecurityGroups(securityGroupList); request.setMinCount(numberOfInstances); request.setMaxCount(numberOfInstances); request.setKeyName(keyPairName); request.setInstanceType(instanceType); if ( instanceProfileArn != null ) { request.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(instanceProfileArn)); } Placement placement = new Placement(); placement.setAvailabilityZone(availabilityZoneName); request.setPlacement(placement); if (userData != null) { request.setUserData(userData); } Reservation initialReservation = ec2.runInstances(request).getReservation(); // If the caller doesn't care about waiting for the instances to come up, go // ahead and return. if (!waitForInstances) { return null; } List<Instance> instances = initialReservation.getInstances(); final Map<String, Instance> pendingInstancesById = new HashMap<>(); for (Instance instance : instances) { pendingInstancesById.put(instance.getInstanceId(), instance); } final List<String> instanceIds = new ArrayList<>(); for (Instance instance : instances) { instanceIds.add(instance.getInstanceId()); } Map<String, Instance> startedInstancesById = new HashMap<>(); do { pauseForInstancesToStartUp(); DescribeInstancesRequest describeRequest = new DescribeInstancesRequest(); describeRequest.setInstanceIds(instanceIds); List<Reservation> reservations = ec2.describeInstances(describeRequest).getReservations(); for (Reservation reservation : reservations) { for (Instance instance : reservation.getInstances()) { // TODO: state codes would be much better... if (instance.getState().getName().equalsIgnoreCase("pending")) { continue; } String instanceId = instance.getInstanceId(); pendingInstancesById.remove(instanceId); startedInstancesById.put(instanceId, instance); } } // TODO: error detection for startup failures } while (!pendingInstancesById.isEmpty()); return new ArrayList<>(startedInstancesById.values()); } /** * Pauses for a few seconds so that instances have a chance to start up. * This method also examines the progress monitor (if set) to see if the * user has canceled the request for which these instances are being * launched. If the request has been canceled, this method will throw an * OperationCanceledException. */ protected void pauseForInstancesToStartUp() throws OperationCanceledException { for (int i = 0; i < 5; i++) { if (progressMonitor != null) { if (progressMonitor.isCanceled()) { throw new OperationCanceledException("Operation canceled while " + "waiting for requested EC2 instances to come online."); } } try {Thread.sleep(1000);} catch (InterruptedException ie) {} } } }
7,183
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/InstanceUtils.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.util.ArrayList; import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; /** * Utilities for looking up instance information based on different criteria. */ public class InstanceUtils { /** The EC2 client to use when looking up instances */ private final AmazonEC2 ec2Client; /** * Constructs a new InstanceUtils object ready to query instance information. * Callers should be aware that this object will always use the specified * so it won't dynamically pick up account changes, region changes, etc. * Callers need to take this into account in their usage. * * @param ec2Client The EC2 client to use when looking up instance. */ public InstanceUtils(AmazonEC2 ec2Client) { this.ec2Client = ec2Client; } /** * Queries EC2 for an instance with the specified instance ID. If no * instance is found with that ID, null is returned. * * @param instanceId * The ID of the instance to look up. * * @return The instance corresponding to the specified ID, otherwise null if * no corresponding instance was found. * * @throws AmazonEC2Exception * If any errors are encountered querying EC2. */ public Instance lookupInstanceById(String instanceId) throws AmazonClientException { return lookupInstanceByIdAndState(instanceId, null); } /** * Queries EC2 for an instance with the specified instance ID and in the * specified state. If no instance is found with that ID and in that state, * null is returned. * * @param instanceId * The ID of the instance to look up. * @param state * The state of the instance to look up. * * @return The instance corresponding to the specified ID and in the * specified state, otherwise null if no corresponding instance is * found. * * @throws AmazonEC2Exception * If any errors are encountered querying EC2. */ public Instance lookupInstanceByIdAndState(String instanceId, String state) throws AmazonClientException { List<String> instanceIds = new ArrayList<>(); instanceIds.add(instanceId); List<Instance> instances = lookupInstancesByIdAndState(instanceIds, state); if (instances.isEmpty()) return null; return instances.get(0); } /** * Queries EC2 for instances with the specified IDs and returns a list of * any that were found. * * @param instanceIds * The list of instance IDs being searched for. * * @return A list of any instances corresponding to instance IDs in the * specified list. * * @throws AmazonEC2Exception * If any errors are encountered querying EC2. */ public List<Instance> lookupInstancesById(List<String> instanceIds) throws AmazonClientException { return lookupInstancesByIdAndState(instanceIds, null); } /** * Queries EC2 for instances with the specified IDs and in the specified * state and returns a list of any that were found. * * @param serviceInstanceIds * The list of instance IDs being searched for. * @param state * The state of the instances being searched for. * * @return A list of any instances corresponding to instance IDs in the * specified list and in the specified state. * * @throws AmazonClientException * If any errors are encountered querying EC2. */ public List<Instance> lookupInstancesByIdAndState(List<String> serviceInstanceIds, String state) throws AmazonClientException { AmazonEC2 ec2 = ec2Client; List<Instance> instances = new ArrayList<>(); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(serviceInstanceIds); DescribeInstancesResult response = ec2.describeInstances(request); List<Reservation> reservations = response.getReservations(); for (Reservation reservation : reservations) { for (Instance instance : reservation.getInstances()) { if (state == null || instance.getState().getName().equals(state)) { instances.add(instance); } } } return instances; } }
7,184
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/TagFormatter.java
/* * Copyright 2009-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.amazonaws.services.ec2.model.Tag; /** * Class that knows how to return a list of tags as text. */ public class TagFormatter { /** * Returns a formatted string representing the tags given. They will be * sorted by their keys. */ public static String formatTags(List<Tag> tags) { if (tags == null || tags.isEmpty()) return ""; Collections.sort(tags, new Comparator<Tag>() { @Override public int compare(Tag o1, Tag o2) { return o1.getKey().compareTo(o2.getKey()); } }); StringBuilder allTags = new StringBuilder(); boolean first = true; for (Tag tag : tags) { if (first) { first = false; } else { allTags.append("; "); } allTags.append(tag.getKey()).append("=").append(tag.getValue()); } return allTags.toString(); } }
7,185
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/Ec2Plugin.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.widgets.Display; import org.osgi.framework.BundleContext; import com.amazonaws.eclipse.core.AWSClientFactory; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin; 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.ec2.keypairs.KeyPairManager; import com.amazonaws.services.ec2.AmazonEC2; /** * The entry point to the EC2 plugin. */ public class Ec2Plugin extends AbstractAwsPlugin { /** The singleton instance of this plugin */ private static Ec2Plugin plugin; /** The ID of this plugin */ public static final String PLUGIN_ID = "com.amazonaws.eclipse.ec2"; /** The id of the AWS Toolkit region preference page */ public static final String REGION_PREFERENCE_PAGE_ID = "com.amazonaws.eclipse.core.ui.preferences.RegionsPreferencePage"; public static final String DEFAULT_EC2_ENDPOINT = "ec2.amazonaws.com"; /** * Returns the singleton instance of this plugin. * * @return The singleton instance of this plugin. */ public static Ec2Plugin getDefault() { return 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; loadInstanceTypes(); Logger rootLogger = Logger.getLogger(""); for (Handler handler : rootLogger.getHandlers()) { rootLogger.removeHandler(handler); } Handler consoleHandler = new ConsoleHandler(); consoleHandler.setLevel(Level.FINE); rootLogger.addHandler(consoleHandler); Logger amazonLogger = Logger.getLogger("com.amazonaws.eclipse"); amazonLogger.setLevel(Level.ALL); for (Handler handler : amazonLogger.getHandlers()) { amazonLogger.removeHandler(handler); } convertLegacyProperties(); } /** * Convenience method to log a status message for this plugin. * * @param status The status to log. */ public static void log(IStatus status) { getDefault().getLog().log(status); } private void loadInstanceTypes() { new Job("Loading Amazon EC2 Instance Types") { @Override protected IStatus run(IProgressMonitor arg0) { InstanceTypes.initialize(); return Status.OK_STATUS; } }.schedule(); } /** * Bootstraps legacy customers to new data storage formats. */ private void convertLegacyProperties() { new Job("Converting legacy EC2 private key files") { @Override protected IStatus run(IProgressMonitor arg0) { try { KeyPairManager.convertLegacyPrivateKeyFiles(); } catch ( Exception ignored ) { // best try } return Status.OK_STATUS; } }.schedule(); } /* (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); } public AmazonEC2 getDefaultEC2Client() { AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(); Region region = RegionUtils.getCurrentRegion(); String regionEndpoint = region.getServiceEndpoints().get(ServiceAbbreviations.EC2); return clientFactory.getEC2ClientByEndpoint(regionEndpoint); } /* (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#createImageRegistry() */ @Override protected ImageRegistry createImageRegistry() { String[] images = new String[] {"add", "/icons/add2.png", "bundle", "/icons/package.png", "clipboard", "/icons/clipboard.png", "configure", "/icons/gear_add.png", "check", "/icons/check2.png", "console", "/icons/console.png", "error", "/icons/error.png", "info", "/icons/info.gif", "launch", "/icons/server_into.png", "reboot", "/icons/replace2.png", "refresh", "/icons/refresh.gif", "remove", "/icons/delete2.png", "snapshot", "/icons/camera.png", "terminate", "/icons/media_stop_red.png", "stop", "/icons/media_pause.png", "start", "/icons/media_play_green.png", "ec2-service", "/icons/ec2-service.png", "filter", "/icons/filter.gif", "status-running", "/icons/green-circle.png", "status-rebooting", "/icons/blue-circle.png", "status-terminated", "/icons/red-circle.png", "status-waiting", "/icons/yellow-circle.png", "server", "/icons/server.png", "volume", "/icons/harddisk.png", "shield", "/icons/shield1.png", "ami", "/icons/ami_icon.png", }; int i = 0; ImageRegistry imageRegistry = new ImageRegistry(Display.getCurrent()); while (i < images.length - 1) { String id = images[i++]; String imagePath = images[i++]; imageRegistry.put(id, ImageDescriptor.createFromFile(getClass(), imagePath)); } return imageRegistry; } }
7,186
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/RemoteFileCopyException.java
/* * Copyright 2009-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.io.IOException; import java.util.List; /** * Exception containing details on a file that failed to be copied to a remote * host correctly. */ public class RemoteFileCopyException extends IOException { /** auto-generated serialization id */ private static final long serialVersionUID = -8004706952817340784L; /** The location the file was to be copied on the remote host */ private final String remoteFile; /** The location of the local file to copy */ private final String localFile; /** A list of the results from each attempt to copy the local file to the remote host */ private final List<RemoteFileCopyResults> resultsFromAllAttempts; /** * Constructs a new RemoteFileCopyException complete with all the results * from each attempt to copy the file to the remote host. * * @param localFile * The local file attempting to be copied. * @param remoteFile * The remote location for the local file to be copied. * @param resultsFromAllAttempts * A list of all the results from each attempt at trying to copy * this file to the remote host. */ public RemoteFileCopyException(String localFile, String remoteFile, List<RemoteFileCopyResults> resultsFromAllAttempts) { super("Unable to copy remote file after trying " + resultsFromAllAttempts.size() + " times"); this.localFile = localFile; this.remoteFile = remoteFile; this.resultsFromAllAttempts = resultsFromAllAttempts; } /* (non-Javadoc) * @see java.lang.Throwable#getMessage() */ @Override public String getMessage() { String superMessage = super.getMessage(); String message = superMessage + "\n\tlocal file: '" + localFile + "'" + "\n\tremote file: '" + remoteFile + "'\n"; if (resultsFromAllAttempts != null && resultsFromAllAttempts.size() > 0) { RemoteFileCopyResults results = resultsFromAllAttempts.get(0); message += "\nResults from first attempt:"; message += "\n\t" + results.getErrorMessage(); if (results.getError() != null) { message += "\n\troot cause: " + results.getError().getMessage(); } message += "\n"; } return message; } }
7,187
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/RemoteCommandUtils.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.ec2.keypairs.KeyPairManager; import com.amazonaws.eclipse.ec2.preferences.PreferenceConstants; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.HostKey; import com.jcraft.jsch.HostKeyRepository; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.UserInfo; /** * Utilities for executing remote commands on EC2 Instances. */ public class RemoteCommandUtils { /** The key pair manager to provide key pairs for remote access */ private static final KeyPairManager keyPairManager = new KeyPairManager(); /** The interval before retrying a remote command */ private static final int RETRY_INTERVAL = 5000; /** The max number of retries for failed remote commands */ private static final int MAX_RETRIES = 3; /** Shared logger */ private static final Logger logger = Logger.getLogger(RemoteCommandUtils.class.getName()); /** * Executes the specified command on the specified instance, possibly * retrying the command a few times if it initially fails for any reason. * * @param command * The command to execute. * @param instance * The instance to execute the command on. * * @return A list with one element for each time the command was attempted, * and a description of the attempt (stdout, stderr, exit code). * * @throws ShellCommandException * If the command is unable to be executed, and fails, even after retrying. */ public List<ShellCommandResults> executeRemoteCommand(String command, Instance instance) throws ShellCommandException { List<ShellCommandResults> results = new LinkedList<>(); while (true) { logger.info("Executing remote command: " + command); ShellCommandResults shellCommandResults = excuteRemoteCommandWithoutRetrying(command, instance); results.add(shellCommandResults); logger.info(" - exit code " + shellCommandResults.exitCode + "\n"); if (shellCommandResults.exitCode == 0) { return results; } if (results.size() >= MAX_RETRIES) { throw new ShellCommandException("Unable to execute the following command:\n" + command, results); } try {Thread.sleep(RETRY_INTERVAL);} catch (InterruptedException ie) {} } } /** * Copies the specified local file to a specified path on the specified * host, possibly retrying if the copy initially failed for any reason. * * @param localFile * The file to copy. * @param remoteFile * The remote location to copy the file to. * @param instance * The instance to copy the file to. * * @throws RemoteFileCopyException * If there were any problems copying the remote file. */ public void copyRemoteFile(String localFile, String remoteFile, Instance instance) throws RemoteFileCopyException { int totalTries = 0; List<RemoteFileCopyResults> allFileCopyAttempts = new ArrayList<>(); while (true) { logger.info("Copying file " + localFile + " to " + instance.getPublicDnsName() + ":" + remoteFile); RemoteFileCopyResults fileCopyResults = copyRemoteFileWithoutRetrying(localFile, remoteFile, instance); if (fileCopyResults.isSucceeded()) return; allFileCopyAttempts.add(fileCopyResults); totalTries++; if (totalTries > MAX_RETRIES) { throw new RemoteFileCopyException(localFile, remoteFile, allFileCopyAttempts); } try {Thread.sleep(RETRY_INTERVAL);} catch (InterruptedException ie) {} } } /** * Executes the specified command locally and waits for it to complete so * the exit status can be returned. Not technically a remote command utility * method, but here for convenience. If command execution fails, the command * will be retried up to three times. * * @param command * The command to execute. * @return The exit status of the command. * * @throws IOException * @throws InterruptedException */ public int executeCommand(String command) throws IOException, InterruptedException { int retries = 3; logger.info("Executing: " + command); /* * We occasionally get problems logging in after an instance * comes up, so we retry the connection a few times after * waiting a few seconds between to make sure the EC2 * firewall has been setup correctly. */ while (true) { Process p = Runtime.getRuntime().exec(command); int exitCode = p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); String errors = ""; String s; while ((s = reader.readLine()) != null) { errors += s; } reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String output = ""; while ((s = reader.readLine()) != null) { output += s; } logger.info(" - exitCode: " + exitCode + "\n" + " - stderr: " + errors + "\n" + " - stdout: " + output); if (exitCode == 0) return 0; if (retries-- < 0) { throw new IOException("Unable to execute command. " + "Exit code: " + exitCode + " errors: '" + errors + "', output = '" + output + "'"); } logger.info("Retrying..."); try {Thread.sleep(RETRY_INTERVAL);} catch(InterruptedException ie) {} } } /* * Private Interface */ /** * Tries to execute the specified command on the specified host one time and * returns the exit code. * * @param command * The remote command to execute. * @param instance * The instance to run the command on. * * @return A description of the attempt to execute this command (stdout, * stderr, exit code). */ private ShellCommandResults excuteRemoteCommandWithoutRetrying(String command, Instance instance) { Session session = null; ChannelExec channel = null; StringBuilder output = new StringBuilder(); StringBuilder errors = new StringBuilder(); try { session = createSshSession(instance); channel = (ChannelExec)session.openChannel("exec"); channel.setCommand(command); channel.setInputStream(null); channel.setErrStream(System.err); try (BufferedInputStream in = new BufferedInputStream(channel.getInputStream()); BufferedInputStream err = new BufferedInputStream(channel.getErrStream())) { channel.connect(); while (true) { drainInputStream(in, output); drainInputStream(err, errors); if (channel.isClosed()) { return new ShellCommandResults( output.toString(), errors.toString(), channel.getExitStatus()); } try {Thread.sleep(1000);} catch (Exception e) {} } } } catch (JSchException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { logger.info(" - output: " + output.toString() + "\n" + " - errors: " + errors.toString()); try {channel.disconnect();} catch (Exception e) {} try {session.disconnect();} catch (Exception e) {} } // TODO: we're missing error message information from JSchException and IOExcetpion. // we could use ShellCommandException to pass it along... return new ShellCommandResults(output.toString(), errors.toString(), 1); } /** * Reads all available data from the specified input stream and writes it to * the specified StringBuiler. * * @param in * The InputStream to read. * @param builder * The StringBuilder to write to. * * @throws IOException * If there were any problems reading from the specified * InputStream. */ private void drainInputStream(InputStream in, StringBuilder builder) throws IOException { BufferedInputStream bufferedInputStream = new BufferedInputStream(in); byte[] buffer = new byte[1024]; while (bufferedInputStream.available() > 0) { int read = bufferedInputStream.read(buffer, 0, buffer.length); if (read > 0) { builder.append(new String(buffer, 0, read)); } } } /** * Tries exactly once to copy the specified file to the specified remote * location and returns a summary of the attempt to copy the local file to * the remote location, indicating if the copy was successful or not. * * @param localFile * The local file to copy. * @param remoteFile * The location to copy the file on the remote host. * @param instance * The remote host to copy the file to. * * @return The results of trying to copy the local file to the remote * location, indicating whether the copy was successful or not as * well as providing information on why it failed if applicable. */ private RemoteFileCopyResults copyRemoteFileWithoutRetrying(String localFile, String remoteFile, Instance instance) { RemoteFileCopyResults results = new RemoteFileCopyResults(localFile, remoteFile); results.setSucceeded(false); Session session = null; ChannelExec channel = null; try { session = createSshSession(instance); String command = "scp -p -t " + remoteFile; channel = (ChannelExec)session.openChannel("exec"); channel.setCommand(command); try (OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); InputStream ext = channel.getExtInputStream()) { StringBuilder extStringBuilder = new StringBuilder(); channel.connect(); if (checkAck(in) != 0) { drainInputStream(ext, extStringBuilder); results.setExternalOutput(extStringBuilder.toString()); results.setErrorMessage("Error connecting to the secure channel for file transfer"); return results; } sendFileHeader(localFile, out); if (checkAck(in) != 0) { drainInputStream(ext, extStringBuilder); results.setExternalOutput(extStringBuilder.toString()); results.setErrorMessage("Error sending file header on the secure channel"); return results; } sendFileData(localFile, out); if (checkAck(in) != 0) { drainInputStream(ext, extStringBuilder); results.setExternalOutput(extStringBuilder.toString()); results.setErrorMessage("Error sending file data on the secure channel"); return results; } } } catch (Exception e) { e.printStackTrace(); results.setErrorMessage("Unexpected exception: " + e.getMessage()); results.setError(e); return results; } finally { try {channel.disconnect();} catch (Exception e) {} try {session.disconnect();} catch (Exception e) {} } results.setSucceeded(true); return results; } /** * Creates a connected SSH session to the specified host. * * @param instance * The EC2 instance to connect to. * * @return The connected session. * * @throws JSchException * @throws IOException */ private Session createSshSession(Instance instance) throws JSchException, IOException { String keyPairFilePath = keyPairManager.lookupKeyPairPrivateKeyFile(AwsToolkitCore.getDefault().getCurrentAccountId(), instance.getKeyName()); if (keyPairFilePath == null) { throw new IOException("No private key file found for key " + instance.getKeyName()); } JSch jsch = new JSch(); jsch.addIdentity(keyPairFilePath); /* * We use a no-op implementation of a host key repository to ensure that * we don't add any hosts to the known_hosts file. Since EC2 hosts are * transient by nature and the DNS names are reused, we want to avoid * any problems with mismatches in the known_hosts file. */ jsch.setHostKeyRepository(new NullHostKeyRepository()); /* * We could configure a session proxy, but if the user has configured a * SOCKS proxy in Eclipse's preferences, we'll automatically use that * since Eclipse sets the socksProxyHost system property. * * We could additionally look for an HTTP/HTTPS proxy and configure * that, but it seems fairly unlikely that the vast majority of * HTTP/HTTPS proxies will be configured to allow SSH traffic through to * a remote host on port 22. * * If that turns out not to be the case, then it'd be easy to look for * an HTTP/HTTPS proxy here and configure the JSch session to use it. * I've already tested that it works for an open HTTP proxy. */ String sshUser = Ec2Plugin.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SSH_USER); Session session = jsch.getSession(sshUser, instance.getPublicDnsName(), 22); // We need this avoid being asked to accept the key session.setConfig("StrictHostKeyChecking", "no"); // Make sure Kerberos authentication is disabled session.setConfig("GSSAPIAuthentication", "no"); /* * These are necessary to avoid problems with latent connections being * closed. This tells JSCH to place a 120 second SO timeout on the * underlying socket. When that interrupt is received, JSCH will send a * keep alive message. This will repeat up to a 1000 times, which should * be more than enough for any long operations to prevent the socket * from being closed. * * SSH has a TCPKeepAlive option, but JSCH doesn't seem to ever check it: * session.setConfig("TCPKeepAlive", "yes"); */ session.setServerAliveInterval(120 * 1000); session.setServerAliveCountMax(1000); session.setConfig("TCPKeepAlive", "yes"); session.connect(); return session; } /** * Sends the SCP file header for the specified file to the specified output * stream. * * @param localFile * The file to generate the header for. * @param out * The output stream to write the header to. * @throws IOException * If there are any problems writing the header. */ private void sendFileHeader(String localFile, OutputStream out) throws IOException { long filesize = (new File(localFile)).length(); String command = "C0644 " + filesize + " "; command += localFile.substring(localFile.lastIndexOf('/') + 1); command += "\n"; out.write(command.getBytes()); out.flush(); } /** * Writes the contents of the specified file to the specified output stream. * * @param localFile * The file to write to the output stream. * @param out * The output stream to write to. * * @throws FileNotFoundException * @throws IOException * If any problems writing the file contents. */ private void sendFileData(String localFile, OutputStream out) throws FileNotFoundException, IOException { try (FileInputStream fis = new FileInputStream(localFile)) { byte[] buf = new byte[1024]; while (true) { int len = fis.read(buf, 0, buf.length); if (len <= 0) break; out.write(buf, 0, len); } } out.write('\0'); out.flush(); } /** * Reads a status byte from the specified input stream and checks its value. * If it's an error code, an error message is read from the input stream as * well. * * @param in * The input stream to read from. * @return The status code read from the input stream. * * @throws IOException * If there were any problems reading from the input stream. */ private static int checkAck(InputStream in) throws IOException { int b = in.read(); // b may be 0 for success, // 1 for error, // 2 for fatal error if (b == 1 || b == 2) { StringBuffer sb = new StringBuffer(); int c; do { c = in.read(); sb.append((char) c); } while (c != '\n'); System.out.print(sb.toString()); } return b; } /** * No-op implementation of HostKeyRepository to ensure that we don't store * host keys for EC2 hosts since EC2 hosts are transient. */ private class NullHostKeyRepository implements HostKeyRepository { @Override public void add(HostKey hostkey, UserInfo ui) {} @Override public int check(String host, byte[] key) { return NOT_INCLUDED; } @Override public HostKey[] getHostKey() { return null; } @Override public HostKey[] getHostKey(String host, String type) { return null; } @Override public String getKnownHostsRepositoryID() { return null; } @Override public void remove(String host, String type) {} @Override public void remove(String host, String type, byte[] key) {} } }
7,188
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/TestAccountInfo.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.io.File; import java.io.FileInputStream; import java.util.Properties; import com.amazonaws.eclipse.core.AccountInfo; /** * Implementation of the AccountInfo class that provides account info during * unit tests. */ public class TestAccountInfo implements AccountInfo { /** The account info properties */ private static final Properties properties = new Properties(); /** The file containing the account info properties */ private static final File testAccountInfoFile; static { File userHome = new File(System.getProperty("user.home")); File ec2Directory = new File(userHome, ".ec2"); testAccountInfoFile = new File(ec2Directory, "awsToolkitTestAccount.properties"); try { properties.load(new FileInputStream(testAccountInfoFile)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Unable to load test account info from " + testAccountInfoFile.getAbsolutePath()); } } @Override public String getAccessKey() { return getProperty("accessKey"); } @Override public String getSecretKey() { return getProperty("secretKey"); } @Override public String getEc2CertificateFile() { return getProperty("ec2CertificateFile"); } @Override public String getEc2PrivateKeyFile() { return getProperty("ec2PrivateKeyFile"); } @Override public String getUserId() { return getProperty("userId"); } @Override public void setAccessKey(String accessKey) { properties.setProperty("accessKey", accessKey); } @Override public void setSecretKey(String secretKey) { properties.setProperty("secretKey", secretKey); } /** * Returns the value of the property with the specified name. The value is * trimmed to ensure that no leading or trailing white space in the property * file will be included. If no propert by the specified name is found, this * method will throw a new RuntimeException. * * @param property * The name of the property to return. * * @return The value of the property with the specified name. */ private String getProperty(String property) { String value = properties.getProperty(property); if (value == null || value.trim().equals("")) { throw new RuntimeException("Unable to load property '" + property + "' from file: " + testAccountInfoFile.getAbsolutePath()); } return value.trim(); } /* Un-implemented methods */ @Override public String getInternalAccountId() { // TODO Auto-generated method stub return null; } @Override public String getAccountName() { // TODO Auto-generated method stub return null; } @Override public void setAccountName(String accountName) { // TODO Auto-generated method stub } @Override public void setUserId(String userId) { // TODO Auto-generated method stub } @Override public void setEc2PrivateKeyFile(String ec2PrivateKeyFile) { // TODO Auto-generated method stub } @Override public void setEc2CertificateFile(String ec2CertificateFile) { // TODO Auto-generated method stub } @Override public void save() { // TODO Auto-generated method stub } @Override public void delete() { // TODO Auto-generated method stub } @Override public boolean isDirty() { // TODO Auto-generated method stub return false; } @Override public boolean isValid() { // TODO Auto-generated method stub return false; } @Override public boolean isCertificateValid() { // TODO Auto-generated method stub return false; } @Override public boolean isUseSessionToken() { // TODO Auto-generated method stub return false; } @Override public void setUseSessionToken(boolean useSessionToken) { // TODO Auto-generated method stub } @Override public String getSessionToken() { // TODO Auto-generated method stub return null; } @Override public void setSessionToken(String sessionToken) { // TODO Auto-generated method stub } }
7,189
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/Ec2PluginConstants.java
/* * Copyright 2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; public class Ec2PluginConstants { public static final String AMIS_VIEW_ID = "com.amazonaws.eclipse.ec2.ui.views.AmiBrowserView"; public static final String INSTANCES_VIEW_ID = "com.amazonaws.eclipse.ec2.ui.views.InstanceView"; public static final String EBS_VIEW_ID = "com.amazonaws.eclipse.ec2.ui.views.ElasticBlockStorageView"; public static final String SECURITY_GROUPS_VIEW_ID = "com.amazonaws.eclipse.ec2.views.SecurityGroupView"; }
7,190
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ShellCommandException.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.io.IOException; import java.util.List; /** * Exception describing a failure of a shell command to execute correctly, * including output from the command, information about retries, etc. */ public class ShellCommandException extends IOException { /** default serial version id */ private static final long serialVersionUID = 1L; /** The results of trying to execute the shell command */ private final List<ShellCommandResults> results; /** * Creates a new ShellCommandException with the specified message and * description of the shell command results. * * @param message * A summary of the shell command failure. * @param results * The results from attempts to execute the command. */ public ShellCommandException(String message, List<ShellCommandResults> results) { super(message); this.results = results; } /** * The results of all attempts to execute the associated command. * * @return The results of all attempts to execute the associated command. */ public List<ShellCommandResults> getShellCommandResults() { return results; } /** * Returns the number of times the associated command was attempted. * * @return The number of times the associated command was attempted. */ public int getNumberOfAttempts() { return results.size(); } }
7,191
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/InstanceTypes.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.ec2; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; import org.apache.http.client.ClientProtocolException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import com.amazonaws.eclipse.core.AwsToolkitHttpClient; import com.amazonaws.eclipse.core.HttpClientFactory; /** * This class describes the available EC2 instance types and the default * instance type to use in UIs. * * Instance type descriptions are loaded from Amazon S3, or from local * descriptions if the S3 metadata isn't available. */ public class InstanceTypes { /** Location of the instance type description metadata */ static final String INSTANCE_TYPES_METADATA_URL = "http://vstoolkit.amazonwebservices.com/ServiceMeta/EC2ServiceMeta.xml"; private static boolean initialized = false; private static List<InstanceType> instanceTypes; private static String defaultInstanceTypeId; private static InstanceType defaultInstanceType; /** * Returns the known Amazon EC2 instance types, attempting to load them from * Amazon S3 if they haven't been loaded yet. */ public static List<InstanceType> getInstanceTypes() { initialize(); return instanceTypes; } /** * Returns the default Amazon EC2 instance type, attempting to load instance * type descriptions from Amazon S3 if they haven't been loaded yet. */ public static InstanceType getDefaultInstanceType() { if (defaultInstanceType != null) return defaultInstanceType; if (defaultInstanceTypeId == null) { Ec2Plugin.log(new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID, "No default instance type available")); } for (InstanceType type : getInstanceTypes()) { if (type.id.equals(defaultInstanceTypeId)) { defaultInstanceType = type; return defaultInstanceType; } } Ec2Plugin.log(new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID, "No instance type found with default type id: " + defaultInstanceTypeId)); return new InstanceType("Small", "m1.small", "N/A", "N/A", 1, "32/64", false, false); } public static synchronized void initialize() { if (initialized) return; initialized = true; // Attempt to load the latest file from S3 try { loadInstanceTypesFromRemote(INSTANCE_TYPES_METADATA_URL); return; } catch (Exception e) { Ec2Plugin.log(new Status(IStatus.WARNING, Ec2Plugin.PLUGIN_ID, "Unable to load Amazon EC2 instance type descriptions from Amazon S3", e)); } // If it fails, then fallback to the file we ship with try { loadInstanceTypes(Ec2Plugin.getDefault().getBundle().getEntry("etc/InstanceTypes.xml")); } catch (IOException e) { Ec2Plugin.log(new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID, "Unable to load Amazon EC2 instance type descriptions from local metadata", e)); } } private static void loadInstanceTypesFromRemote(String url) throws ClientProtocolException, IOException { AwsToolkitHttpClient client = HttpClientFactory.create(Ec2Plugin.getDefault(), url); try (InputStream inputStream = client.getEntityContent(url)) { if (inputStream == null) { return; } loadInstanceTypesFromInputStream(inputStream); } } private static void loadInstanceTypes(URL url) throws IOException { try (InputStream inputStream = url.openStream()) { loadInstanceTypesFromInputStream(inputStream); } } private static void loadInstanceTypesFromInputStream(InputStream inputStream) throws IOException { InstanceTypesParser parser = new InstanceTypesParser(inputStream); instanceTypes = parser.parseInstanceTypes(); defaultInstanceTypeId = parser.parseDefaultInstanceTypeId(); } }
7,192
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ShellCommandResults.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; /** * Simple data object describing the details of an attempt to execute a shell * command, including error code, stdout, stderr, etc. */ public class ShellCommandResults { /** The output generated by the shell command */ public final String output; /** The error output generated by the shell command */ public final String errorOutput; /** The exit code of the shell command */ public final int exitCode; /** * Constructs a new ShellCommandResults object. * * @param output * The contents of STDOUT. * @param errorOutput * The contents of STDERR. * @param exitCode * The exit code of the shell command. */ public ShellCommandResults(String output, String errorOutput, int exitCode) { this.output = output; this.errorOutput = errorOutput; this.exitCode = exitCode; } }
7,193
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/AmiToolsVersion.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.text.ParseException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents the version number of the AMI bundling tools. */ public class AmiToolsVersion { private final int majorVersion; private final int minorVersion; private final int patch; private static final String regex = "^(\\d+)\\.(\\d+)-(\\d+)\\s*.*"; private static final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL); /** * Constructs a new version object directly from major, minor, and patch * version numbers. * * @param majorVersion * The major version for this new version object. * @param minorVersion * The minor version for this new version object. * @param patch * The patch version for this new version object. */ public AmiToolsVersion(int majorVersion, int minorVersion, int patch) { this.majorVersion = majorVersion; this.minorVersion = minorVersion; this.patch = patch; } /** * Constructs a new version object by parsing a version string, which is * assumed to be of the form: * <major-version>.<minor-version>-<patch-version> * * @param versionString * The version string to parse for the major, minor and patch * version numbers. * * @throws ParseException * If the version string parameter was not able to be parsed * into the expected format. */ public AmiToolsVersion(String versionString) throws ParseException { String parseExceptionMessage = "Version string '" + versionString + "' does not start with version number in the form " + "'<major-version>.<minor-version>-<patch-version>'"; Matcher matcher = pattern.matcher(versionString); if (! matcher.matches()) { throw new ParseException(parseExceptionMessage, -1); } try { majorVersion = Integer.parseInt(matcher.group(1)); minorVersion = Integer.parseInt(matcher.group(2)); patch = Integer.parseInt(matcher.group(3)); } catch (Throwable t) { throw new ParseException(parseExceptionMessage, -1); } } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return majorVersion + "." + minorVersion + "-" + patch; } /** * Returns true if this version is greater than the specified version. * * @param other * The other version to compare against. * * @return True if this version is greater than the other specified * version. */ public boolean isGreaterThan(AmiToolsVersion other) { if (this.majorVersion > other.majorVersion) { return true; } else if (this.majorVersion < other.majorVersion) { return false; } if (this.minorVersion > other.minorVersion) { return true; } else if (this.minorVersion < other.minorVersion) { return false; } if (this.patch > other.patch) { return true; } else if (this.patch < other.patch) { return false; } return false; } /** * Returns the major version component of this version number. * * @return The major version component of this version number. */ public int getMajorVersion() { return majorVersion; } /** * Returns the minor version component of this version number. * * @return The minor version component of this version number. */ public int getMinorVersion() { return minorVersion; } /** * Returns the patch component of this version number. * * @return The patch component of this version number. */ public int getPatch() { return patch; } }
7,194
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/RemoteFileCopyResults.java
/* * Copyright 2009-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; /** * Represents the results of an attempt to copy a local file to a remote host. */ public class RemoteFileCopyResults { /** The local file being copied */ private final String localFile; /** The remote destination file */ private final String remoteFile; /** True if the file was successfully copied to the remote location */ private boolean succeeded; /** An optional error message if the remote file copy was not successful */ private String errorMessage; /** An optional exception describing why this attempt failed */ private Exception error; /** * An optional string containing the external output from the copy command * such as any error messages from the command used for the copy */ private String externalOutput; /** * Creates a new RemoteFileCopyResults object describing the results of * copying the specified local file to the specified remote file location. * * @param localFile * The local file being copied. * @param remoteFile * The remote file location. */ public RemoteFileCopyResults(String localFile, String remoteFile) { this.localFile = localFile; this.remoteFile = remoteFile; } /** * @return The local file location. */ public String getLocalFile() { return localFile; } /** * @return The remote file location. */ public String getRemoteFile() { return remoteFile; } /** * @param errorMessage * the error message describing how this remote file copy failed. */ public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } /** * @return the error message describing how this remote file copy attempt * failed. */ public String getErrorMessage() { if (externalOutput == null || externalOutput.trim().length() == 0) { return errorMessage; } return errorMessage + ":\n\t" + externalOutput; } /** * @param wasSuccessful * True if the file was successfully copied to the remote file * location. */ public void setSucceeded(boolean wasSuccessful) { this.succeeded = wasSuccessful; } /** * @return True if the file was successfully copied to the remote file * location. */ public boolean isSucceeded() { return succeeded; } /** * @param error the error to set */ public void setError(Exception error) { this.error = error; } /** * @return the error */ public Exception getError() { return error; } /** * @param externalOutput * The command output from the attempt to copy the file to the * remote location. */ public void setExternalOutput(String externalOutput) { this.externalOutput = externalOutput; } }
7,195
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/PlatformUtils.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import java.io.File; import static com.amazonaws.eclipse.core.util.OsPlatformUtils.isWindows; import static com.amazonaws.eclipse.core.util.OsPlatformUtils.isMac; import static com.amazonaws.eclipse.core.util.OsPlatformUtils.isLinux; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.logging.Logger; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.statushandlers.StatusManager; import com.amazonaws.eclipse.ec2.preferences.PreferenceConstants; /** * Basic utilities for working with platform differences. */ public class PlatformUtils { private static final String PPK_CONVERTER_EXE = "/lib/PemToPPKConverter.exe"; private static final Logger logger = Logger.getLogger(PlatformUtils.class.getName()); /** * Returns true if the platform specific SSH client is correctly configured * and ready to be used on this system. * * @return True if the platform specific SSH client is correctly configured * and ready to be used on this system. */ public boolean isSshClientConfigured() { if (isWindows()) { String puttyPath = Ec2Plugin.getDefault().getPreferenceStore().getString(PreferenceConstants.P_PUTTY_EXECUTABLE); // First make sure something is specified... if (puttyPath == null || puttyPath.length() == 0) return false; // Next make sure it's a file if (! new File(puttyPath).isFile()) return false; } return true; } /** * Opens a shell to the specified host using a platform specific terminal * window. * * @param user * The user to connect to the remote host as. * @param host * The remote host to connect to. * @param identityFile * The file containing the identity file for the connection. * @throws IOException * If any problems are encountered opening the remote shell. */ public void openShellToRemoteHost(String user, String host, String identityFile) throws IOException, InterruptedException, URISyntaxException { IPreferenceStore preferenceStore = Ec2Plugin.getDefault().getPreferenceStore(); String sshOptions = preferenceStore.getString(PreferenceConstants.P_SSH_OPTIONS); String sshCommand = preferenceStore.getString(PreferenceConstants.P_SSH_CLIENT); sshCommand += " " + sshOptions + " -i " + identityFile + " " + user + "@" + host; if (isMac()) { URL locationUrl = FileLocator.find(Ec2Plugin.getDefault().getBundle(),new Path("/"), null); URL fileUrl = FileLocator.toFileURL(locationUrl); executeAsynchronousCommand(new String[] {"osascript", fileUrl.getFile() + "scripts/openMacTerminalShell.scpt", sshCommand}); } else if (isLinux()) { String terminalCommand = preferenceStore.getString(PreferenceConstants.P_TERMINAL_EXECUTABLE); executeAsynchronousCommand(new String[] {terminalCommand, "-e", sshCommand}); } else if (isWindows()) { openRemoteShellFromWindows(user, host, identityFile); } else { String osName = System.getProperty("os.name"); Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID, "Unable to determine what platform '" + osName + "' is."); StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG); } } /* * Private Interface */ /** * Opens a remote shell connection from a windows host as the specified user * to the specified host using the OpenSSH identity file to authenticate. * This method assumes that the user has already configured their SSH tools * (PuTTY), so it doesn't check for that, but it does check to see if the * required PuTTY private key exists, and if it doesn't, it will convert it. * * @param user * The user to log into the remote host as. * @param host * The host to connect to. * @param identityFile * The OpenSSH private key file that provides the user * passwordless access to the specified host. * @throws IOException * If any problems are encountered executing the SSH client. */ private void openRemoteShellFromWindows(String user, String host, String identityFile) throws IOException, InterruptedException, URISyntaxException { String puttyExecutable = Ec2Plugin.getDefault().getPreferenceStore().getString( PreferenceConstants.P_PUTTY_EXECUTABLE); File privateKeyFile = new File(identityFile); if (!privateKeyFile.isFile()) { throw new IOException("Unable to find the required OpenSSH private key '" + identityFile + "'."); } String puttyPrivateKeyFile = translateOpenSshPrivateKeyFileToPuttyPrivateKeyFile(identityFile); File ppkFile = new File(puttyPrivateKeyFile); if (! ppkFile.exists()) { executeAsynchronousCommand(new String[] {getPuttyGenConversionExecutable(), "\"" + identityFile + "\"", "\"" + ppkFile.getAbsolutePath() + "\""}).waitFor(); } String[] openShellCommand = new String[] {puttyExecutable, "-ssh", "-i", puttyPrivateKeyFile, user + "@" + host}; executeAsynchronousCommand(openShellCommand); } /** * Returns the path to the bundled puttygen conversion utility * @throws IOException */ private String getPuttyGenConversionExecutable() throws URISyntaxException, IOException { URL conversionExe = FileLocator.resolve(FileLocator.find(Ec2Plugin.getDefault().getBundle(), new Path(PPK_CONVERTER_EXE), null)); return new File(conversionExe.toURI()).getAbsolutePath(); } /** * Translates the full path to an OpenSSH private key file to a full path * for the corresponding PuTTY private key file. * * @param identityFile * The full path to an OpenSSH private key file. * * @return The full path for the corresponding PuTTY private key. * * @throws IOException * If any problems were encountered translating the OpenSSH * private key file path. */ private String translateOpenSshPrivateKeyFileToPuttyPrivateKeyFile(String identityFile) throws IOException { int suffixIndex = identityFile.lastIndexOf("."); if (suffixIndex < 0) { throw new IOException("Unable to translate '" + identityFile + "' to a PuTTY private key file path."); } String puttyPrivateKeyFile = identityFile.substring(0, suffixIndex); puttyPrivateKeyFile = puttyPrivateKeyFile + ".ppk"; return puttyPrivateKeyFile; } /** * Executes the specified command array, but does NOT wait for it to finish, * therefore no exit code is returned. * * @param commandArray * The command array to execute. * @throws IOException * If there were any problems kicking off the command. */ public Process executeAsynchronousCommand(String[] commandArray) throws IOException { String commandString = ""; for (String command : commandArray) { commandString += command + " "; } logger.info("Executing: " + commandString); return Runtime.getRuntime().exec(commandArray); } }
7,196
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/InstanceTypesParser.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.ec2; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; class InstanceTypesParser { // Tag names for the instance type description file private static final String ID = "id"; private static final String REQUIRES_EBS_VOLUME = "RequiresEBSVolume"; private static final String REQUIRES_HVM_IMAGE = "RequiresHvmImage"; private static final String ARCHITECTURE_BITS = "ArchitectureBits"; private static final String VIRTUAL_CORES = "VirtualCores"; private static final String MEMORY = "Memory"; private static final String DISK_SPACE = "DiskSpace"; private static final String INSTANCE_TYPE = "InstanceType"; private static final String DISPLAY_NAME = "DisplayName"; private static final String DEFAULT_INSTANCE_TYPE = "DefaultInstanceType"; private Document doc; /** * Creates a new parser for instance type metadata that reads from the * specified InputStream. * * @param inputStream * The stream to read instance type metadata from. * * @throws IOException * If there were any problems reading from the stream. */ public InstanceTypesParser(InputStream inputStream) throws IOException { try { doc = parseDocument(inputStream); } catch (Exception e) { throw new IOException("Unable to parse instance type descriptions", e); } } /** * Returns a list of the InstanceType objects parsed from the provided * descriptions. */ public List<InstanceType> parseInstanceTypes() { LinkedList<InstanceType> instanceTypes = new LinkedList<>(); NodeList instanceTypeNodeList = doc.getElementsByTagName(INSTANCE_TYPE); for (int i = 0; i < instanceTypeNodeList.getLength(); i++) { Node instanceTypeNode = instanceTypeNodeList.item(i); instanceTypes.add(parseInstanceTypeElement(instanceTypeNode)); } return instanceTypes; } /** * Returns the default instance type specified in the instance type * descriptions. */ public String parseDefaultInstanceTypeId() { NodeList nodes = doc.getElementsByTagName(DEFAULT_INSTANCE_TYPE); return getAttribute(nodes.item(0), ID); } private Document parseDocument(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(inputStream); doc.getDocumentElement().normalize(); return doc; } /** * Parses an InstanceType element from the document: * <InstanceType id="t1.micro"> * <DisplayName>Micro</DisplayName> * <Memory>613 MB</Memory> * <DiskSpace>0 (EBS only)</DiskSpace> * <VirtualCores>1</VirtualCores> * <ArchitectureBits>32/64</ArchitectureBits> * <RequiresEBSVolume>true</RequiresEBSVolume> * <RequiresHvmImage>false</RequiresHvmImage> * </InstanceType> */ private InstanceType parseInstanceTypeElement(Node instanceTypeNode) { String id = getAttribute(instanceTypeNode, ID); String displayName = null; String memory = null; String diskSpace = null; String architecture = null; int virtualCores = 0; boolean requiresEbsVolume = false; boolean requiresHvmImage = false; Node node = instanceTypeNode.getFirstChild(); do { String nodeName = node.getNodeName(); if (nodeName.equals(DISPLAY_NAME)) { displayName = getChildText(node); } else if (nodeName.equals(MEMORY)) { memory = getChildText(node); } else if (nodeName.equals(DISK_SPACE)) { diskSpace = getChildText(node); } else if (nodeName.equals(VIRTUAL_CORES)) { virtualCores = parseInt(node); } else if (nodeName.equals(ARCHITECTURE_BITS)) { architecture = getChildText(node); } else if (nodeName.equals(REQUIRES_EBS_VOLUME)) { requiresEbsVolume = Boolean.parseBoolean(getChildText(node)); } else if (nodeName.equals(REQUIRES_HVM_IMAGE)) { requiresHvmImage = Boolean.parseBoolean(getChildText(node)); } } while ((node = node.getNextSibling()) != null); return new InstanceType(displayName, id, memory, diskSpace, virtualCores, architecture, requiresEbsVolume, requiresHvmImage); } private int parseInt(Node node) { try { return Integer.parseInt(getChildText(node)); } catch (NumberFormatException nfe) { Status status = new Status(IStatus.WARNING, Ec2Plugin.PLUGIN_ID, "Error parsing Amazon EC2 instance type", nfe); Ec2Plugin.getDefault().getLog().log(status); return -1; } } private String getAttribute(Node node, String attributeName) { return node.getAttributes().getNamedItem(attributeName).getTextContent(); } private String getChildText(Node node) { return node.getFirstChild().getTextContent(); } }
7,197
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/InstanceType.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2; import com.amazonaws.services.ec2.model.Image; /** * Represents a type of Amazon EC2 instance, including information on memory, * disk space, architecture, etc. */ public class InstanceType { /** The presentation/display name of this instance type. */ public final String name; /** The EC2 ID for this instance type. */ public final String id; /** The RAM (with units) available on this instance type. */ public final String memoryWithUnits; /** The disk space (with units) available on this instance type. */ public final String diskSpaceWithUnits; /** The number of virtual cores available on this instance type. */ public final int numberOfVirtualCores; /** The architecture type (32, 64, or 32/64) on this instance type. */ public final String architectureBits; /** Whether this instance type supports 32-bit AMIs */ public final boolean supports32Bit; /** Whether this instance type supports 64-bit AMIs */ public final boolean supports64Bit; /** Whether this instance type requires an EBS-backed image */ public final boolean requiresEbsVolume; /** Whether this instance type requires images using hardware virtualization */ public final boolean requiresHvmImage; public InstanceType(String name, String id, String memoryWithUnits, String diskSpaceWithUnits, int virtualCores, String architecture, boolean requiresEbsVolume) { this(name, id, memoryWithUnits, diskSpaceWithUnits, virtualCores, architecture, requiresEbsVolume, false); } public InstanceType(String name, String id, String memoryWithUnits, String diskSpaceWithUnits, int virtualCores, String architecture, boolean requiresEbsVolume, boolean requiresHvmImage) { this.name = name; this.id = id; this.diskSpaceWithUnits = diskSpaceWithUnits; this.memoryWithUnits = memoryWithUnits; this.numberOfVirtualCores = virtualCores; this.architectureBits = architecture; this.requiresEbsVolume = requiresEbsVolume; this.requiresHvmImage = requiresHvmImage; this.supports32Bit = architecture.contains("32"); this.supports64Bit = architecture.contains("64"); } /** * Returns whether a new instance of this type can be launched with * a specified image. */ public boolean canLaunch(Image image) { if ( image == null ) return false; int requiredArchitectureBits = 32; if ( image.getArchitecture().equalsIgnoreCase("x86_64") ) { requiredArchitectureBits = 64; } if ( (requiredArchitectureBits == 64 && !supports64Bit) || (requiredArchitectureBits == 32 && !supports32Bit) ) return false; if ( requiresEbsVolume && !image.getRootDeviceType().equalsIgnoreCase("ebs") ) return false; if ( requiresHvmImage && !image.getVirtualizationType().equalsIgnoreCase("hvm") ) return false; return true; } }
7,198
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/ChargeWarningComposite.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.ec2.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; 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 com.amazonaws.eclipse.ec2.Ec2Plugin; /** * Simple composite that displays a message to make sure users understand that * launching EC2 instances will charge their account. */ public class ChargeWarningComposite extends Composite { /** * Creates a new ChargeWarningComposite as a child in the specified * composite, with the specified styling information. * * @param parent * The parent composite that will contain this new * ChargeWarningComposite. * @param style * The styling bits for this new Composite. */ public ChargeWarningComposite(Composite parent, int style) { super(parent, style); setLayout(new GridLayout(2, false)); Label infoIconLabel = new Label(this, SWT.NONE); infoIconLabel.setImage(Ec2Plugin.getDefault().getImageRegistry().get("info")); infoIconLabel.setLayoutData(new GridData()); Label infoLabel = new Label(this, SWT.WRAP); infoLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); infoLabel.setText("You will be charged the hourly rate for any instances you launch until you successfully shut them down."); italicizeLabel(infoLabel); } /* * Private Interface */ /** * Changes the font style on the specified label so that the text is * displayed in italics. * * @param label * The label to change. */ private void italicizeLabel(Label label) { Font font = label.getFont(); FontData[] fontDataArray = font.getFontData(); for (FontData fontData : fontDataArray) { fontData.setStyle(SWT.ITALIC); } Font newFont = new Font(Display.getDefault(), fontDataArray); label.setFont(newFont); } }
7,199