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.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/PasswordPolicyForm.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.statushandlers.StatusManager; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.model.GetAccountPasswordPolicyResult; import com.amazonaws.services.identitymanagement.model.PasswordPolicy; import com.amazonaws.services.identitymanagement.model.UpdateAccountPasswordPolicyRequest; class PasswordPolicyForm extends Composite { private Label headerLabel; private Text minCharacterLable; private Button requireUpppercaseButton; private Button requireLowercaseButtion; private Button requireNumbersButton; private Button requireSymbolsButton; private Button allowChangePasswordButton; private Button applyPolicyButton; private Button deletePolicyButton; private AmazonIdentityManagement iam; public PasswordPolicyForm(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) { super(parent, SWT.NONE); this.iam = iam; GridDataFactory gridDataFactory = GridDataFactory.swtDefaults() .align(SWT.BEGINNING, SWT.TOP).grab(true, false).minSize(200, SWT.DEFAULT).hint(200, SWT.DEFAULT); this.setLayout(new GridLayout(2, false)); this.setBackground(toolkit.getColors().getBackground()); GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalSpan = 2; Composite comp = toolkit.createComposite(this); comp.setLayoutData(gridData); comp.setLayout(new GridLayout(2, false)); toolkit.createLabel(comp, "").setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_INFORMATION)); headerLabel = toolkit.createLabel(comp, ""); gridDataFactory.copy().minSize(SWT.MAX, SWT.MAX).applyTo(headerLabel); toolkit.createLabel(this, "Minimum Password Length:"); minCharacterLable = new Text(this, SWT.BORDER | SWT.WRAP | SWT.NONE); gridDataFactory.applyTo(minCharacterLable); requireUpppercaseButton = toolkit.createButton(this, "", SWT.CHECK); toolkit.createLabel(this, "Require at least one uppercase letter"); requireLowercaseButtion = toolkit.createButton(this, "", SWT.CHECK); toolkit.createLabel(this, "Require at least one lowercase letter"); requireNumbersButton = toolkit.createButton(this, "", SWT.CHECK); toolkit.createLabel(this, "Require at least one number"); requireSymbolsButton = toolkit.createButton(this, "", SWT.CHECK); toolkit.createLabel(this, "Require at least one non-alphanumeric character"); allowChangePasswordButton = toolkit.createButton(this, "", SWT.CHECK); toolkit.createLabel(this, "Allow users to change their own password"); applyPolicyButton = toolkit.createButton(this, "Apply Password Policy", SWT.PUSH); applyPolicyButton.addSelectionListener(new AddPasswordPolicySelectionListener()); deletePolicyButton = toolkit.createButton(this, "Delete Password Policy", SWT.PUSH); deletePolicyButton.addSelectionListener(new DeletePasswordPolicySelectionLister()); refresh(); } private class AddPasswordPolicySelectionListener implements SelectionListener { @Override public void widgetSelected(SelectionEvent e) { final UpdateAccountPasswordPolicyRequest updateAccountPasswordPolicyRequest = new UpdateAccountPasswordPolicyRequest(); updateAccountPasswordPolicyRequest.setAllowUsersToChangePassword(allowChangePasswordButton.getSelection()); updateAccountPasswordPolicyRequest.setMinimumPasswordLength(Integer.parseInt(minCharacterLable.getText())); updateAccountPasswordPolicyRequest.setRequireLowercaseCharacters(requireLowercaseButtion.getSelection()); updateAccountPasswordPolicyRequest.setRequireUppercaseCharacters(requireUpppercaseButton.getSelection()); updateAccountPasswordPolicyRequest.setRequireSymbols(requireSymbolsButton.getSelection()); updateAccountPasswordPolicyRequest.setRequireNumbers(requireNumbersButton.getSelection()); new Job("Adding password policy") { @Override protected IStatus run(IProgressMonitor monitor) { try { iam.updateAccountPasswordPolicy(updateAccountPasswordPolicyRequest); refresh(); return Status.OK_STATUS; } catch (Exception e) { return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to add the password policy: " + e.getMessage(), e); } } }.schedule(); } @Override public void widgetDefaultSelected(SelectionEvent e) { return; } } private class DeletePasswordPolicySelectionLister implements SelectionListener { @Override public void widgetSelected(SelectionEvent e) { new Job("Deleting password policy") { @Override protected IStatus run(IProgressMonitor monitor) { try { iam.deleteAccountPasswordPolicy(); refresh(); return Status.OK_STATUS; } catch (Exception e) { return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to delete the password policy: " + e.getMessage(), e); } } }.schedule(); } @Override public void widgetDefaultSelected(SelectionEvent e) { return; } } public void refresh() { new LoadPasswordPolicyThread().start(); } private class LoadPasswordPolicyThread extends Thread { private PasswordPolicy getPasswordPolicy() { GetAccountPasswordPolicyResult getAccountPasswordPolicyResult = null; try { getAccountPasswordPolicyResult = iam.getAccountPasswordPolicy(); } catch (Exception e) { return null; } return getAccountPasswordPolicyResult.getPasswordPolicy(); } @Override public void run() { final PasswordPolicy passwordPolicy = getPasswordPolicy(); try { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (passwordPolicy != null) { headerLabel.setText("Modify your existing password policy below."); minCharacterLable.setText(passwordPolicy.getMinimumPasswordLength().toString()); requireLowercaseButtion.setSelection(passwordPolicy.getRequireLowercaseCharacters()); requireUpppercaseButton.setSelection(passwordPolicy.getRequireUppercaseCharacters()); requireNumbersButton.setSelection(passwordPolicy.getRequireNumbers()); requireSymbolsButton.setSelection(passwordPolicy.getRequireSymbols()); allowChangePasswordButton.setSelection(passwordPolicy.getAllowUsersToChangePassword()); deletePolicyButton.setEnabled(true); } else { headerLabel.setText("Currently, this AWS account does not have a password policy. Specify a password policy below."); minCharacterLable.setText(""); requireLowercaseButtion.setSelection(false); requireUpppercaseButton.setSelection(false); requireNumbersButton.setSelection(false); requireSymbolsButton.setSelection(false); allowChangePasswordButton.setSelection(false); deletePolicyButton.setEnabled(false); } } }); } catch (Exception e) { Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to describe password policy", e); StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW); } } } }
7,500
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/OpenRolesEditorAction.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; public class OpenRolesEditorAction extends AbstractOpenEditorAction { private final static String EDITOR_ID = "com.amazonaws.eclipse.explorer.identitymanagement.role.roleEditor"; public OpenRolesEditorAction(String titleName) { super(titleName, EDITOR_ID); } }
7,501
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/AbstractUserTable.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.statushandlers.StatusManager; import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.model.User; public abstract class AbstractUserTable extends Composite { protected TableViewer viewer; protected final EditorInput userEditorInput; protected final UserTableContentProvider contentProvider; protected List<User> users; protected AmazonIdentityManagement iam; protected final class UserTableContentProvider extends ArrayContentProvider { private User[] users; @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput instanceof User[]) { users = (User[]) newInput; } else { users = new User[0]; } } @Override public Object[] getElements(Object inputElement) { return users; } public User getItemByIndex(int index) { return users[index]; } } protected final class userTableLabelProvider 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 User == false) return ""; User user = (User) element; switch (columnIndex) { case 0: return user.getUserName(); case 1: return user.getCreateDate().toString(); } return element.toString(); } } public AbstractUserTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit, EditorInput userEditorInput) { super(parent, SWT.NONE); this.userEditorInput = userEditorInput; this.iam = iam; this.setLayoutData(new GridData(GridData.FILL_BOTH)); TableColumnLayout tableColumnLayout = new TableColumnLayout(); this.setLayout(tableColumnLayout); contentProvider = new UserTableContentProvider(); userTableLabelProvider labelProvider = new userTableLabelProvider(); viewer = new TableViewer(this, SWT.BORDER | SWT.MULTI); viewer.getTable().setLinesVisible(true); viewer.getTable().setHeaderVisible(true); viewer.setLabelProvider(labelProvider); viewer.setContentProvider(contentProvider); createColumns(tableColumnLayout, viewer.getTable()); refresh(); } public abstract void refresh(); protected abstract void listUsers(); private void createColumns(TableColumnLayout columnLayout, Table table) { createColumn(table, columnLayout, "User Name"); createColumn(table, columnLayout, "Creation Time"); } private TableColumn createColumn(Table table, TableColumnLayout columnLayout, String text) { TableColumn column = new TableColumn(table, SWT.NONE); column.setText(text); column.setMoveable(true); columnLayout.setColumnData(column, new ColumnWeightData(30)); return column; } protected class LoadUserTableThread extends Thread { public LoadUserTableThread() { // TODO Auto-generated constructor stub } @Override public void run() { try { listUsers(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (users == null) { viewer.setInput(null); } else { viewer.setInput(users.toArray(new User[users.size()])); } } }); } catch (Exception e) { Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to describe users", e); StatusManager.getManager().handle(status, StatusManager.LOG); } } } }
7,502
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/ExplorerSorter.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; import org.eclipse.jface.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,503
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/PasswordPolicyEditor.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; 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.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.part.EditorPart; import com.amazonaws.eclipse.core.AWSClientFactory; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; public class PasswordPolicyEditor extends EditorPart { private EditorInput editorInput; private PasswordPolicyForm passwordPolicyForm; private AmazonIdentityManagement iam; @Override public void doSave(IProgressMonitor monitor) { } @Override public void doSaveAs() { } @Override public void init(IEditorSite site, IEditorInput input) { setSite(site); setInput(input); setPartName(input.getName()); this.editorInput = (EditorInput) input; iam = getClient(); } @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } @Override public void createPartControl(Composite parent) { FormToolkit toolkit = new FormToolkit(Display.getDefault()); ScrolledForm form = new ScrolledForm(parent, SWT.V_SCROLL); form.setExpandHorizontal(true); form.setExpandVertical(true); form.setBackground(toolkit.getColors().getBackground()); form.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); form.setFont(JFaceResources.getHeaderFont()); form.setText(getFormTitle()); toolkit.decorateFormHeading(form.getForm()); form.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_KEY)); form.getBody().setLayout(new GridLayout()); passwordPolicyForm = new PasswordPolicyForm(iam, form.getBody(), toolkit); passwordPolicyForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); form.getToolBarManager().add(new RefreshAction()); form.getToolBarManager().update(true); } private String getFormTitle() { String formTitle = editorInput.getName(); return formTitle; } @Override public void setFocus() { } protected AmazonIdentityManagement getClient() { AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(editorInput.getAccountId()); return clientFactory.getIAMClientByEndpoint(editorInput.getRegionEndpoint()); } private class RefreshAction extends Action { public RefreshAction() { this.setText("Refresh"); this.setToolTipText("Refresh"); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH)); } @Override public void run() { passwordPolicyForm.refresh(); } } }
7,504
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/AbstractPolicyTable.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.statushandlers.StatusManager; import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; /** * Base class for list policies in a table for user, group and role. */ public abstract class AbstractPolicyTable extends Composite { protected TableViewer viewer; protected List<String> policyNames; protected TableContentProvider contentProvider; protected AmazonIdentityManagement iam; protected AbstractPolicyTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) { super(parent, SWT.NONE); this.iam = iam; TableColumnLayout tableColumnLayout = new TableColumnLayout(); this.setLayout(tableColumnLayout); this.setLayoutData(new GridData(GridData.FILL_BOTH)); contentProvider = new TableContentProvider(); TableLabelProvider labelProvider = new TableLabelProvider(); viewer = new TableViewer(this, SWT.SINGLE | SWT.BORDER ); viewer.getTable().setLinesVisible(true); viewer.getTable().setHeaderVisible(true); viewer.setLabelProvider(labelProvider); viewer.setContentProvider(contentProvider); createColumns(tableColumnLayout, viewer.getTable()); } protected void createColumns(TableColumnLayout columnLayout, Table table) { createColumn(table, columnLayout, "Policy Name"); } 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 ColumnWeightData(30)); return column; } protected class TableContentProvider extends ArrayContentProvider { private String[] policyNames; @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput instanceof String[]) policyNames = (String[]) newInput; else policyNames = new String[0]; } @Override public Object[] getElements(Object inputElement) { return policyNames; } public String getItemByIndex(int index) { return policyNames[index]; } } protected class TableLabelProvider 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 String == false) return ""; String policyName = (String) element; return policyName; } } abstract public void refresh(); abstract protected void getPolicyNames(); protected class LoadPermissionTableThread extends Thread { public LoadPermissionTableThread() { // TODO Auto-generated constructor stub } @Override public void run() { try { getPolicyNames(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (policyNames == null) { viewer.setInput(null); } else { viewer.setInput(policyNames.toArray(new String[policyNames.size()])); } } }); } catch (Exception e) { Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to list policies", e); StatusManager.getManager().handle(status, StatusManager.LOG); } } } }
7,505
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/IdentityManagementContentProvider.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; import java.util.ArrayList; import java.util.List; 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.ExplorerNode; import com.amazonaws.eclipse.explorer.Loading; public class IdentityManagementContentProvider extends AbstractContentProvider { public static final class IdentityManagementRootElement { public static final IdentityManagementRootElement ROOT_ELEMENT = new IdentityManagementRootElement(); } public static class UserNode extends ExplorerNode { public UserNode() { super("Users", 1, loadImage(AwsToolkitCore.IMAGE_USER), new OpenUserEditorAction("Users")); } } public static class GroupNode extends ExplorerNode { public GroupNode() { super("Groups", 0, loadImage(AwsToolkitCore.IMAGE_GROUP), new OpenGroupEditorAction("Groups")); } } public static class RoleNode extends ExplorerNode { public RoleNode() { super("Roles", 2, loadImage(AwsToolkitCore.IMAGE_ROLE), new OpenRolesEditorAction("Roles")); } } public static class PasswordPolicyNode extends ExplorerNode { public PasswordPolicyNode() { super("Password Policy", 3, loadImage(AwsToolkitCore.IMAGE_KEY), new OpenPasswordPolicyEditorAction("Password Policy")); } } @Override public boolean hasChildren(Object element) { return (element instanceof AWSResourcesRootElement || element instanceof IdentityManagementRootElement); } @Override public Object[] loadChildren(Object parentElement) { if (parentElement instanceof AWSResourcesRootElement) { return new Object[] { IdentityManagementRootElement.ROOT_ELEMENT }; } if (parentElement instanceof IdentityManagementRootElement) { List<ExplorerNode> iamNodes = new ArrayList<>(); ExplorerNode userNode = new UserNode(); iamNodes.add(userNode); ExplorerNode groupNode = new GroupNode(); iamNodes.add(groupNode); ExplorerNode roleNode = new RoleNode(); iamNodes.add(roleNode); ExplorerNode passworPolicyNode = new PasswordPolicyNode(); iamNodes.add(passworPolicyNode); return iamNodes.toArray(); } return Loading.LOADING; } @Override public String getServiceAbbreviation() { return ServiceAbbreviations.IAM; } }
7,506
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/IdentityManagementExplorerActionProvider.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.navigator.CommonActionProvider; import com.amazonaws.eclipse.explorer.identitymanagement.IdentityManagementContentProvider.GroupNode; import com.amazonaws.eclipse.explorer.identitymanagement.IdentityManagementContentProvider.IdentityManagementRootElement; import com.amazonaws.eclipse.explorer.identitymanagement.IdentityManagementContentProvider.RoleNode; import com.amazonaws.eclipse.explorer.identitymanagement.IdentityManagementContentProvider.UserNode; /** * Action provider when right-clicking on IAM nodes in the explorer. */ public class IdentityManagementExplorerActionProvider extends CommonActionProvider { /* * (non-Javadoc) * * @see * org.eclipse.ui.actions.ActionGroup#fillContextMenu(org.eclipse.jface. * action.IMenuManager) */ @Override public void fillContextMenu(IMenuManager menu) { StructuredSelection selection = (StructuredSelection) getActionSite() .getStructuredViewer().getSelection(); if (selection.size() != 1) return; if (selection.getFirstElement() instanceof IdentityManagementRootElement || selection.getFirstElement() instanceof UserNode) { menu.add(new CreateUserAction()); } if (selection.getFirstElement() instanceof IdentityManagementRootElement || selection.getFirstElement() instanceof GroupNode) { menu.add(new CreateGroupAction()); } if (selection.getFirstElement() instanceof IdentityManagementRootElement || selection.getFirstElement() instanceof RoleNode) { menu.add(new CreateRoleAction()); } } }
7,507
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/OpenUserEditorAction.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; public class OpenUserEditorAction extends AbstractOpenEditorAction { private static final String EDITOR_ID = "com.amazonaws.eclipse.explorer.identitymanagement.user.userEditor"; public OpenUserEditorAction(String titleName) { super(titleName, EDITOR_ID); } }
7,508
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/OpenGroupEditorAction.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; public class OpenGroupEditorAction extends AbstractOpenEditorAction { private final static String EDITOR_ID = "com.amazonaws.eclipse.explorer.identitymanagement.group.groupEditor"; public OpenGroupEditorAction(String titleName) { super(titleName, EDITOR_ID); } }
7,509
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/CreateGroupAction.java
/* * Copyright 2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.explorer.identitymanagement; import org.eclipse.jface.action.Action; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.ui.IRefreshable; import com.amazonaws.eclipse.identitymanagement.group.CreateGroupWizard; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; public class CreateGroupAction extends Action { private final IRefreshable refreshable; private AmazonIdentityManagement iam; public CreateGroupAction(AmazonIdentityManagement iam, IRefreshable refreshable) { this.refreshable = refreshable; setToolTipText("Create New Group"); this.iam = iam; } public CreateGroupAction(IRefreshable refreshable) { this(null, refreshable); } public CreateGroupAction() { this(null, null); } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD); } @Override public String getText() { return "Create New Group"; } @Override public void run() { WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new CreateGroupWizard(iam, refreshable)); dialog.open(); } }
7,510
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/AbstractTelemetryClient.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry; import javax.annotation.Generated; import software.amazon.awssdk.services.toolkittelemetry.model.*; /** * Abstract implementation of {@code TelemetryClient}. */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AbstractTelemetryClient implements TelemetryClient { protected AbstractTelemetryClient() { } @Override public PostErrorReportResult postErrorReport(PostErrorReportRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public PostFeedbackResult postFeedback(PostFeedbackRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public PostMetricsResult postMetrics(PostMetricsRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public void shutdown() { throw new java.lang.UnsupportedOperationException(); } }
7,511
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/TelemetryClientClient.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry; import java.util.*; import javax.annotation.Generated; import com.amazonaws.http.*; import com.amazonaws.protocol.json.*; import com.amazonaws.annotation.ThreadSafe; import com.amazonaws.client.AwsSyncClientParams; import com.amazonaws.client.ClientHandler; import com.amazonaws.client.ClientHandlerParams; import com.amazonaws.client.ClientExecutionParams; import com.amazonaws.opensdk.protect.client.SdkClientHandler; import com.amazonaws.SdkBaseException; import software.amazon.awssdk.services.toolkittelemetry.model.*; import software.amazon.awssdk.services.toolkittelemetry.model.transform.*; /** * Client for accessing ToolkitTelemetry. All service calls made using this client are blocking, and will not return * until the service call completes. * <p> * */ @ThreadSafe @Generated("com.amazonaws:aws-java-sdk-code-generator") class TelemetryClientClient implements TelemetryClient { private final ClientHandler clientHandler; private static final com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl protocolFactory = new com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl( new JsonClientMetadata().withProtocolVersion("1.1").withSupportsCbor(false).withSupportsIon(false).withContentTypeOverride("application/json") .withBaseServiceExceptionClass(software.amazon.awssdk.services.toolkittelemetry.model.TelemetryClientException.class)); /** * Constructs a new client to invoke service methods on ToolkitTelemetry using the specified parameters. * * <p> * All service calls made using this new client object are blocking, and will not return until the service call * completes. * * @param clientParams * Object providing client parameters. */ TelemetryClientClient(AwsSyncClientParams clientParams) { this.clientHandler = new SdkClientHandler(new ClientHandlerParams().withClientParams(clientParams)); } /** * @param postErrorReportRequest * @return Result of the PostErrorReport operation returned by the service. * @sample TelemetryClient.PostErrorReport */ @Override public PostErrorReportResult postErrorReport(PostErrorReportRequest postErrorReportRequest) { HttpResponseHandler<PostErrorReportResult> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true) .withHasStreamingSuccessResponse(false), new PostErrorReportResultJsonUnmarshaller()); HttpResponseHandler<SdkBaseException> errorResponseHandler = createErrorResponseHandler(); return clientHandler.execute(new ClientExecutionParams<PostErrorReportRequest, PostErrorReportResult>() .withMarshaller(new PostErrorReportRequestProtocolMarshaller(protocolFactory)).withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler).withInput(postErrorReportRequest)); } /** * @param postFeedbackRequest * @return Result of the PostFeedback operation returned by the service. * @sample TelemetryClient.PostFeedback */ @Override public PostFeedbackResult postFeedback(PostFeedbackRequest postFeedbackRequest) { HttpResponseHandler<PostFeedbackResult> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true) .withHasStreamingSuccessResponse(false), new PostFeedbackResultJsonUnmarshaller()); HttpResponseHandler<SdkBaseException> errorResponseHandler = createErrorResponseHandler(); return clientHandler.execute(new ClientExecutionParams<PostFeedbackRequest, PostFeedbackResult>() .withMarshaller(new PostFeedbackRequestProtocolMarshaller(protocolFactory)).withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler).withInput(postFeedbackRequest)); } /** * @param postMetricsRequest * @return Result of the PostMetrics operation returned by the service. * @sample TelemetryClient.PostMetrics */ @Override public PostMetricsResult postMetrics(PostMetricsRequest postMetricsRequest) { HttpResponseHandler<PostMetricsResult> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true) .withHasStreamingSuccessResponse(false), new PostMetricsResultJsonUnmarshaller()); HttpResponseHandler<SdkBaseException> errorResponseHandler = createErrorResponseHandler(); return clientHandler.execute(new ClientExecutionParams<PostMetricsRequest, PostMetricsResult>() .withMarshaller(new PostMetricsRequestProtocolMarshaller(protocolFactory)).withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler).withInput(postMetricsRequest)); } /** * Create the error response handler for the operation. * * @param errorShapeMetadata * Error metadata for the given operation * @return Configured error response handler to pass to HTTP layer */ private HttpResponseHandler<SdkBaseException> createErrorResponseHandler(JsonErrorShapeMetadata... errorShapeMetadata) { return protocolFactory.createErrorResponseHandler(new JsonErrorResponseMetadata().withErrorShapes(Arrays.asList(errorShapeMetadata))); } @Override public void shutdown() { clientHandler.shutdown(); } }
7,512
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/TelemetryClient.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry; import javax.annotation.Generated; import software.amazon.awssdk.services.toolkittelemetry.model.*; /** * Interface for accessing ToolkitTelemetry. */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public interface TelemetryClient { /** * @param postErrorReportRequest * @return Result of the PostErrorReport operation returned by the service. * @sample TelemetryClient.PostErrorReport */ PostErrorReportResult postErrorReport(PostErrorReportRequest postErrorReportRequest); /** * @param postFeedbackRequest * @return Result of the PostFeedback operation returned by the service. * @sample TelemetryClient.PostFeedback */ PostFeedbackResult postFeedback(PostFeedbackRequest postFeedbackRequest); /** * @param postMetricsRequest * @return Result of the PostMetrics operation returned by the service. * @sample TelemetryClient.PostMetrics */ PostMetricsResult postMetrics(PostMetricsRequest postMetricsRequest); /** * @return Create new instance of builder with all defaults set. */ public static TelemetryClientClientBuilder builder() { return new TelemetryClientClientBuilder(); } /** * Shuts down this client object, releasing any resources that might be held open. This is an optional method, and * callers are not expected to call it, but can if they want to explicitly release any open resources. Once a client * has been shutdown, it should not be used to make any more requests. */ void shutdown(); }
7,513
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/package-info.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry;
7,514
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/TelemetryClientClientBuilder.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry; import com.amazonaws.annotation.NotThreadSafe; import com.amazonaws.client.AwsSyncClientParams; import com.amazonaws.opensdk.protect.client.SdkSyncClientBuilder; import com.amazonaws.opensdk.internal.config.ApiGatewayClientConfigurationFactory; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.Signer; import com.amazonaws.util.RuntimeHttpUtils; import com.amazonaws.Protocol; import java.net.URI; import javax.annotation.Generated; /** * Fluent builder for {@link software.amazon.awssdk.services.toolkittelemetry.TelemetryClient}. * * @see software.amazon.awssdk.services.toolkittelemetry.TelemetryClient#builder **/ @NotThreadSafe @Generated("com.amazonaws:aws-java-sdk-code-generator") public final class TelemetryClientClientBuilder extends SdkSyncClientBuilder<TelemetryClientClientBuilder, TelemetryClient> { private static final URI DEFAULT_ENDPOINT = RuntimeHttpUtils.toUri("https://client-telemetry.us-east-1.amazonaws.com", Protocol.HTTPS); private static final String DEFAULT_REGION = "us-east-1"; /** * Package private constructor - builder should be created via {@link TelemetryClient#builder()} */ TelemetryClientClientBuilder() { super(new ApiGatewayClientConfigurationFactory()); } /** * Specify an implementation of {@link AWSCredentialsProvider} to be used when signing IAM auth'd requests * * @param iamCredentials * the credential provider */ @Override public void setIamCredentials(AWSCredentialsProvider iamCredentials) { super.setIamCredentials(iamCredentials); } /** * Specify an implementation of {@link AWSCredentialsProvider} to be used when signing IAM auth'd requests * * @param iamCredentials * the credential provider * @return This object for method chaining. */ public TelemetryClientClientBuilder iamCredentials(AWSCredentialsProvider iamCredentials) { setIamCredentials(iamCredentials); return this; } /** * Sets the IAM region to use when using IAM auth'd requests against a service in any of it's non-default regions. * This is only expected to be used when a custom endpoint has also been set. * * @param iamRegion * the IAM region string to use when signing */ public void setIamRegion(String iamRegion) { super.setIamRegion(iamRegion); } /** * Sets the IAM region to use when using IAM auth'd requests against a service in any of it's non-default regions. * This is only expected to be used when a custom endpoint has also been set. * * @param iamRegion * the IAM region string to use when signing * @return This object for method chaining. */ public TelemetryClientClientBuilder iamRegion(String iamRegion) { setIamRegion(iamRegion); return this; } /** * Construct a synchronous implementation of TelemetryClient using the current builder configuration. * * @param params * Current builder configuration represented as a parameter object. * @return Fully configured implementation of TelemetryClient. */ @Override protected TelemetryClient build(AwsSyncClientParams params) { return new TelemetryClientClient(params); } @Override protected URI defaultEndpoint() { return DEFAULT_ENDPOINT; } @Override protected String defaultRegion() { return DEFAULT_REGION; } @Override protected Signer defaultIamSigner() { return signerFactory().createSigner(); } }
7,515
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/PostMetricsRequest.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.auth.RequestSigner; import com.amazonaws.opensdk.protect.auth.RequestSignerAware; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostMetricsRequest extends com.amazonaws.opensdk.BaseRequest implements Serializable, Cloneable, RequestSignerAware { private String aWSProduct; private String aWSProductVersion; private String clientID; private String oS; private String oSVersion; private String parentProduct; private String parentProductVersion; private java.util.List<MetricDatum> metricData; /** * @param aWSProduct * @see AWSProduct */ public void setAWSProduct(String aWSProduct) { this.aWSProduct = aWSProduct; } /** * @return * @see AWSProduct */ public String getAWSProduct() { return this.aWSProduct; } /** * @param aWSProduct * @return Returns a reference to this object so that method calls can be chained together. * @see AWSProduct */ public PostMetricsRequest aWSProduct(String aWSProduct) { setAWSProduct(aWSProduct); return this; } /** * @param aWSProduct * @see AWSProduct */ public void setAWSProduct(AWSProduct aWSProduct) { aWSProduct(aWSProduct); } /** * @param aWSProduct * @return Returns a reference to this object so that method calls can be chained together. * @see AWSProduct */ public PostMetricsRequest aWSProduct(AWSProduct aWSProduct) { this.aWSProduct = aWSProduct.toString(); return this; } /** * @param aWSProductVersion */ public void setAWSProductVersion(String aWSProductVersion) { this.aWSProductVersion = aWSProductVersion; } /** * @return */ public String getAWSProductVersion() { return this.aWSProductVersion; } /** * @param aWSProductVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest aWSProductVersion(String aWSProductVersion) { setAWSProductVersion(aWSProductVersion); return this; } /** * @param clientID */ public void setClientID(String clientID) { this.clientID = clientID; } /** * @return */ public String getClientID() { return this.clientID; } /** * @param clientID * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest clientID(String clientID) { setClientID(clientID); return this; } /** * @param oS */ public void setOS(String oS) { this.oS = oS; } /** * @return */ public String getOS() { return this.oS; } /** * @param oS * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest oS(String oS) { setOS(oS); return this; } /** * @param oSVersion */ public void setOSVersion(String oSVersion) { this.oSVersion = oSVersion; } /** * @return */ public String getOSVersion() { return this.oSVersion; } /** * @param oSVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest oSVersion(String oSVersion) { setOSVersion(oSVersion); return this; } /** * @param parentProduct */ public void setParentProduct(String parentProduct) { this.parentProduct = parentProduct; } /** * @return */ public String getParentProduct() { return this.parentProduct; } /** * @param parentProduct * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest parentProduct(String parentProduct) { setParentProduct(parentProduct); return this; } /** * @param parentProductVersion */ public void setParentProductVersion(String parentProductVersion) { this.parentProductVersion = parentProductVersion; } /** * @return */ public String getParentProductVersion() { return this.parentProductVersion; } /** * @param parentProductVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest parentProductVersion(String parentProductVersion) { setParentProductVersion(parentProductVersion); return this; } /** * @return */ public java.util.List<MetricDatum> getMetricData() { return metricData; } /** * @param metricData */ public void setMetricData(java.util.Collection<MetricDatum> metricData) { if (metricData == null) { this.metricData = null; return; } this.metricData = new java.util.ArrayList<MetricDatum>(metricData); } /** * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setMetricData(java.util.Collection)} or {@link #withMetricData(java.util.Collection)} if you want to * override the existing values. * </p> * * @param metricData * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest metricData(MetricDatum... metricData) { if (this.metricData == null) { setMetricData(new java.util.ArrayList<MetricDatum>(metricData.length)); } for (MetricDatum ele : metricData) { this.metricData.add(ele); } return this; } /** * @param metricData * @return Returns a reference to this object so that method calls can be chained together. */ public PostMetricsRequest metricData(java.util.Collection<MetricDatum> metricData) { setMetricData(metricData); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAWSProduct() != null) sb.append("AWSProduct: ").append(getAWSProduct()).append(","); if (getAWSProductVersion() != null) sb.append("AWSProductVersion: ").append(getAWSProductVersion()).append(","); if (getClientID() != null) sb.append("ClientID: ").append(getClientID()).append(","); if (getOS() != null) sb.append("OS: ").append(getOS()).append(","); if (getOSVersion() != null) sb.append("OSVersion: ").append(getOSVersion()).append(","); if (getParentProduct() != null) sb.append("ParentProduct: ").append(getParentProduct()).append(","); if (getParentProductVersion() != null) sb.append("ParentProductVersion: ").append(getParentProductVersion()).append(","); if (getMetricData() != null) sb.append("MetricData: ").append(getMetricData()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PostMetricsRequest == false) return false; PostMetricsRequest other = (PostMetricsRequest) obj; if (other.getAWSProduct() == null ^ this.getAWSProduct() == null) return false; if (other.getAWSProduct() != null && other.getAWSProduct().equals(this.getAWSProduct()) == false) return false; if (other.getAWSProductVersion() == null ^ this.getAWSProductVersion() == null) return false; if (other.getAWSProductVersion() != null && other.getAWSProductVersion().equals(this.getAWSProductVersion()) == false) return false; if (other.getClientID() == null ^ this.getClientID() == null) return false; if (other.getClientID() != null && other.getClientID().equals(this.getClientID()) == false) return false; if (other.getOS() == null ^ this.getOS() == null) return false; if (other.getOS() != null && other.getOS().equals(this.getOS()) == false) return false; if (other.getOSVersion() == null ^ this.getOSVersion() == null) return false; if (other.getOSVersion() != null && other.getOSVersion().equals(this.getOSVersion()) == false) return false; if (other.getParentProduct() == null ^ this.getParentProduct() == null) return false; if (other.getParentProduct() != null && other.getParentProduct().equals(this.getParentProduct()) == false) return false; if (other.getParentProductVersion() == null ^ this.getParentProductVersion() == null) return false; if (other.getParentProductVersion() != null && other.getParentProductVersion().equals(this.getParentProductVersion()) == false) return false; if (other.getMetricData() == null ^ this.getMetricData() == null) return false; if (other.getMetricData() != null && other.getMetricData().equals(this.getMetricData()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAWSProduct() == null) ? 0 : getAWSProduct().hashCode()); hashCode = prime * hashCode + ((getAWSProductVersion() == null) ? 0 : getAWSProductVersion().hashCode()); hashCode = prime * hashCode + ((getClientID() == null) ? 0 : getClientID().hashCode()); hashCode = prime * hashCode + ((getOS() == null) ? 0 : getOS().hashCode()); hashCode = prime * hashCode + ((getOSVersion() == null) ? 0 : getOSVersion().hashCode()); hashCode = prime * hashCode + ((getParentProduct() == null) ? 0 : getParentProduct().hashCode()); hashCode = prime * hashCode + ((getParentProductVersion() == null) ? 0 : getParentProductVersion().hashCode()); hashCode = prime * hashCode + ((getMetricData() == null) ? 0 : getMetricData().hashCode()); return hashCode; } @Override public PostMetricsRequest clone() { return (PostMetricsRequest) super.clone(); } @Override public Class<? extends RequestSigner> signerType() { return com.amazonaws.opensdk.protect.auth.IamRequestSigner.class; } /** * Set the configuration for this request. * * @param sdkRequestConfig * Request configuration. * @return This object for method chaining. */ public PostMetricsRequest sdkRequestConfig(com.amazonaws.opensdk.SdkRequestConfig sdkRequestConfig) { super.sdkRequestConfig(sdkRequestConfig); return this; } }
7,516
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/Unit.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum Unit { Milliseconds("Milliseconds"), Bytes("Bytes"), Percent("Percent"), Count("Count"), None("None"); private String value; private Unit(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return Unit corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static Unit fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (Unit enumEntry : Unit.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
7,517
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/PostFeedbackRequest.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.auth.RequestSigner; import com.amazonaws.opensdk.protect.auth.RequestSignerAware; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostFeedbackRequest extends com.amazonaws.opensdk.BaseRequest implements Serializable, Cloneable, RequestSignerAware { private String aWSProduct; private String aWSProductVersion; private String oS; private String oSVersion; private String parentProduct; private String parentProductVersion; private java.util.List<MetadataEntry> metadata; private String sentiment; private String comment; /** * @param aWSProduct * @see AWSProduct */ public void setAWSProduct(String aWSProduct) { this.aWSProduct = aWSProduct; } /** * @return * @see AWSProduct */ public String getAWSProduct() { return this.aWSProduct; } /** * @param aWSProduct * @return Returns a reference to this object so that method calls can be chained together. * @see AWSProduct */ public PostFeedbackRequest aWSProduct(String aWSProduct) { setAWSProduct(aWSProduct); return this; } /** * @param aWSProduct * @see AWSProduct */ public void setAWSProduct(AWSProduct aWSProduct) { aWSProduct(aWSProduct); } /** * @param aWSProduct * @return Returns a reference to this object so that method calls can be chained together. * @see AWSProduct */ public PostFeedbackRequest aWSProduct(AWSProduct aWSProduct) { this.aWSProduct = aWSProduct.toString(); return this; } /** * @param aWSProductVersion */ public void setAWSProductVersion(String aWSProductVersion) { this.aWSProductVersion = aWSProductVersion; } /** * @return */ public String getAWSProductVersion() { return this.aWSProductVersion; } /** * @param aWSProductVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostFeedbackRequest aWSProductVersion(String aWSProductVersion) { setAWSProductVersion(aWSProductVersion); return this; } /** * @param oS */ public void setOS(String oS) { this.oS = oS; } /** * @return */ public String getOS() { return this.oS; } /** * @param oS * @return Returns a reference to this object so that method calls can be chained together. */ public PostFeedbackRequest oS(String oS) { setOS(oS); return this; } /** * @param oSVersion */ public void setOSVersion(String oSVersion) { this.oSVersion = oSVersion; } /** * @return */ public String getOSVersion() { return this.oSVersion; } /** * @param oSVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostFeedbackRequest oSVersion(String oSVersion) { setOSVersion(oSVersion); return this; } /** * @param parentProduct */ public void setParentProduct(String parentProduct) { this.parentProduct = parentProduct; } /** * @return */ public String getParentProduct() { return this.parentProduct; } /** * @param parentProduct * @return Returns a reference to this object so that method calls can be chained together. */ public PostFeedbackRequest parentProduct(String parentProduct) { setParentProduct(parentProduct); return this; } /** * @param parentProductVersion */ public void setParentProductVersion(String parentProductVersion) { this.parentProductVersion = parentProductVersion; } /** * @return */ public String getParentProductVersion() { return this.parentProductVersion; } /** * @param parentProductVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostFeedbackRequest parentProductVersion(String parentProductVersion) { setParentProductVersion(parentProductVersion); return this; } /** * @return */ public java.util.List<MetadataEntry> getMetadata() { return metadata; } /** * @param metadata */ public void setMetadata(java.util.Collection<MetadataEntry> metadata) { if (metadata == null) { this.metadata = null; return; } this.metadata = new java.util.ArrayList<MetadataEntry>(metadata); } /** * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setMetadata(java.util.Collection)} or {@link #withMetadata(java.util.Collection)} if you want to override * the existing values. * </p> * * @param metadata * @return Returns a reference to this object so that method calls can be chained together. */ public PostFeedbackRequest metadata(MetadataEntry... metadata) { if (this.metadata == null) { setMetadata(new java.util.ArrayList<MetadataEntry>(metadata.length)); } for (MetadataEntry ele : metadata) { this.metadata.add(ele); } return this; } /** * @param metadata * @return Returns a reference to this object so that method calls can be chained together. */ public PostFeedbackRequest metadata(java.util.Collection<MetadataEntry> metadata) { setMetadata(metadata); return this; } /** * @param sentiment * @see Sentiment */ public void setSentiment(String sentiment) { this.sentiment = sentiment; } /** * @return * @see Sentiment */ public String getSentiment() { return this.sentiment; } /** * @param sentiment * @return Returns a reference to this object so that method calls can be chained together. * @see Sentiment */ public PostFeedbackRequest sentiment(String sentiment) { setSentiment(sentiment); return this; } /** * @param sentiment * @see Sentiment */ public void setSentiment(Sentiment sentiment) { sentiment(sentiment); } /** * @param sentiment * @return Returns a reference to this object so that method calls can be chained together. * @see Sentiment */ public PostFeedbackRequest sentiment(Sentiment sentiment) { this.sentiment = sentiment.toString(); return this; } /** * @param comment */ public void setComment(String comment) { this.comment = comment; } /** * @return */ public String getComment() { return this.comment; } /** * @param comment * @return Returns a reference to this object so that method calls can be chained together. */ public PostFeedbackRequest comment(String comment) { setComment(comment); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAWSProduct() != null) sb.append("AWSProduct: ").append(getAWSProduct()).append(","); if (getAWSProductVersion() != null) sb.append("AWSProductVersion: ").append(getAWSProductVersion()).append(","); if (getOS() != null) sb.append("OS: ").append(getOS()).append(","); if (getOSVersion() != null) sb.append("OSVersion: ").append(getOSVersion()).append(","); if (getParentProduct() != null) sb.append("ParentProduct: ").append(getParentProduct()).append(","); if (getParentProductVersion() != null) sb.append("ParentProductVersion: ").append(getParentProductVersion()).append(","); if (getMetadata() != null) sb.append("Metadata: ").append(getMetadata()).append(","); if (getSentiment() != null) sb.append("Sentiment: ").append(getSentiment()).append(","); if (getComment() != null) sb.append("Comment: ").append(getComment()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PostFeedbackRequest == false) return false; PostFeedbackRequest other = (PostFeedbackRequest) obj; if (other.getAWSProduct() == null ^ this.getAWSProduct() == null) return false; if (other.getAWSProduct() != null && other.getAWSProduct().equals(this.getAWSProduct()) == false) return false; if (other.getAWSProductVersion() == null ^ this.getAWSProductVersion() == null) return false; if (other.getAWSProductVersion() != null && other.getAWSProductVersion().equals(this.getAWSProductVersion()) == false) return false; if (other.getOS() == null ^ this.getOS() == null) return false; if (other.getOS() != null && other.getOS().equals(this.getOS()) == false) return false; if (other.getOSVersion() == null ^ this.getOSVersion() == null) return false; if (other.getOSVersion() != null && other.getOSVersion().equals(this.getOSVersion()) == false) return false; if (other.getParentProduct() == null ^ this.getParentProduct() == null) return false; if (other.getParentProduct() != null && other.getParentProduct().equals(this.getParentProduct()) == false) return false; if (other.getParentProductVersion() == null ^ this.getParentProductVersion() == null) return false; if (other.getParentProductVersion() != null && other.getParentProductVersion().equals(this.getParentProductVersion()) == false) return false; if (other.getMetadata() == null ^ this.getMetadata() == null) return false; if (other.getMetadata() != null && other.getMetadata().equals(this.getMetadata()) == false) return false; if (other.getSentiment() == null ^ this.getSentiment() == null) return false; if (other.getSentiment() != null && other.getSentiment().equals(this.getSentiment()) == false) return false; if (other.getComment() == null ^ this.getComment() == null) return false; if (other.getComment() != null && other.getComment().equals(this.getComment()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAWSProduct() == null) ? 0 : getAWSProduct().hashCode()); hashCode = prime * hashCode + ((getAWSProductVersion() == null) ? 0 : getAWSProductVersion().hashCode()); hashCode = prime * hashCode + ((getOS() == null) ? 0 : getOS().hashCode()); hashCode = prime * hashCode + ((getOSVersion() == null) ? 0 : getOSVersion().hashCode()); hashCode = prime * hashCode + ((getParentProduct() == null) ? 0 : getParentProduct().hashCode()); hashCode = prime * hashCode + ((getParentProductVersion() == null) ? 0 : getParentProductVersion().hashCode()); hashCode = prime * hashCode + ((getMetadata() == null) ? 0 : getMetadata().hashCode()); hashCode = prime * hashCode + ((getSentiment() == null) ? 0 : getSentiment().hashCode()); hashCode = prime * hashCode + ((getComment() == null) ? 0 : getComment().hashCode()); return hashCode; } @Override public PostFeedbackRequest clone() { return (PostFeedbackRequest) super.clone(); } @Override public Class<? extends RequestSigner> signerType() { return com.amazonaws.opensdk.protect.auth.IamRequestSigner.class; } /** * Set the configuration for this request. * * @param sdkRequestConfig * Request configuration. * @return This object for method chaining. */ public PostFeedbackRequest sdkRequestConfig(com.amazonaws.opensdk.SdkRequestConfig sdkRequestConfig) { super.sdkRequestConfig(sdkRequestConfig); return this; } }
7,518
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/MetricDatum.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MetricDatum implements Serializable, Cloneable, StructuredPojo { private String metricName; private Long epochTimestamp; private String unit; private Double value; private java.util.List<MetadataEntry> metadata; /** * @param metricName */ public void setMetricName(String metricName) { this.metricName = metricName; } /** * @return */ public String getMetricName() { return this.metricName; } /** * @param metricName * @return Returns a reference to this object so that method calls can be chained together. */ public MetricDatum metricName(String metricName) { setMetricName(metricName); return this; } /** * @param epochTimestamp */ public void setEpochTimestamp(Long epochTimestamp) { this.epochTimestamp = epochTimestamp; } /** * @return */ public Long getEpochTimestamp() { return this.epochTimestamp; } /** * @param epochTimestamp * @return Returns a reference to this object so that method calls can be chained together. */ public MetricDatum epochTimestamp(Long epochTimestamp) { setEpochTimestamp(epochTimestamp); return this; } /** * @param unit * @see Unit */ public void setUnit(String unit) { this.unit = unit; } /** * @return * @see Unit */ public String getUnit() { return this.unit; } /** * @param unit * @return Returns a reference to this object so that method calls can be chained together. * @see Unit */ public MetricDatum unit(String unit) { setUnit(unit); return this; } /** * @param unit * @see Unit */ public void setUnit(Unit unit) { unit(unit); } /** * @param unit * @return Returns a reference to this object so that method calls can be chained together. * @see Unit */ public MetricDatum unit(Unit unit) { this.unit = unit.toString(); return this; } /** * @param value */ public void setValue(Double value) { this.value = value; } /** * @return */ public Double getValue() { return this.value; } /** * @param value * @return Returns a reference to this object so that method calls can be chained together. */ public MetricDatum value(Double value) { setValue(value); return this; } /** * @return */ public java.util.List<MetadataEntry> getMetadata() { return metadata; } /** * @param metadata */ public void setMetadata(java.util.Collection<MetadataEntry> metadata) { if (metadata == null) { this.metadata = null; return; } this.metadata = new java.util.ArrayList<MetadataEntry>(metadata); } /** * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setMetadata(java.util.Collection)} or {@link #withMetadata(java.util.Collection)} if you want to override * the existing values. * </p> * * @param metadata * @return Returns a reference to this object so that method calls can be chained together. */ public MetricDatum metadata(MetadataEntry... metadata) { if (this.metadata == null) { setMetadata(new java.util.ArrayList<MetadataEntry>(metadata.length)); } for (MetadataEntry ele : metadata) { this.metadata.add(ele); } return this; } /** * @param metadata * @return Returns a reference to this object so that method calls can be chained together. */ public MetricDatum metadata(java.util.Collection<MetadataEntry> metadata) { setMetadata(metadata); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMetricName() != null) sb.append("MetricName: ").append(getMetricName()).append(","); if (getEpochTimestamp() != null) sb.append("EpochTimestamp: ").append(getEpochTimestamp()).append(","); if (getUnit() != null) sb.append("Unit: ").append(getUnit()).append(","); if (getValue() != null) sb.append("Value: ").append(getValue()).append(","); if (getMetadata() != null) sb.append("Metadata: ").append(getMetadata()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof MetricDatum == false) return false; MetricDatum other = (MetricDatum) obj; if (other.getMetricName() == null ^ this.getMetricName() == null) return false; if (other.getMetricName() != null && other.getMetricName().equals(this.getMetricName()) == false) return false; if (other.getEpochTimestamp() == null ^ this.getEpochTimestamp() == null) return false; if (other.getEpochTimestamp() != null && other.getEpochTimestamp().equals(this.getEpochTimestamp()) == false) return false; if (other.getUnit() == null ^ this.getUnit() == null) return false; if (other.getUnit() != null && other.getUnit().equals(this.getUnit()) == false) return false; if (other.getValue() == null ^ this.getValue() == null) return false; if (other.getValue() != null && other.getValue().equals(this.getValue()) == false) return false; if (other.getMetadata() == null ^ this.getMetadata() == null) return false; if (other.getMetadata() != null && other.getMetadata().equals(this.getMetadata()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMetricName() == null) ? 0 : getMetricName().hashCode()); hashCode = prime * hashCode + ((getEpochTimestamp() == null) ? 0 : getEpochTimestamp().hashCode()); hashCode = prime * hashCode + ((getUnit() == null) ? 0 : getUnit().hashCode()); hashCode = prime * hashCode + ((getValue() == null) ? 0 : getValue().hashCode()); hashCode = prime * hashCode + ((getMetadata() == null) ? 0 : getMetadata().hashCode()); return hashCode; } @Override public MetricDatum clone() { try { return (MetricDatum) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { software.amazon.awssdk.services.toolkittelemetry.model.transform.MetricDatumMarshaller.getInstance().marshall(this, protocolMarshaller); } }
7,519
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/TelemetryClientException.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import com.amazonaws.opensdk.SdkErrorHttpMetadata; import com.amazonaws.opensdk.internal.BaseException; import com.amazonaws.annotation.SdkInternalApi; import javax.annotation.Generated; /** * Base exception for all service exceptions thrown by A beautiful and amazing ToolkitTelemetry */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class TelemetryClientException extends com.amazonaws.SdkBaseException implements BaseException { private static final long serialVersionUID = 1L; private SdkErrorHttpMetadata sdkHttpMetadata; private String message; /** * Constructs a new TelemetryClientException with the specified error message. * * @param message * Describes the error encountered. */ public TelemetryClientException(String message) { super(message); this.message = message; } @Override public TelemetryClientException sdkHttpMetadata(SdkErrorHttpMetadata sdkHttpMetadata) { this.sdkHttpMetadata = sdkHttpMetadata; return this; } @Override public SdkErrorHttpMetadata sdkHttpMetadata() { return sdkHttpMetadata; } @SdkInternalApi @Override public void setMessage(String message) { this.message = message; } @Override public String getMessage() { return message; } }
7,520
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/PostFeedbackResult.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostFeedbackResult extends com.amazonaws.opensdk.BaseResult implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PostFeedbackResult == false) return false; PostFeedbackResult other = (PostFeedbackResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public PostFeedbackResult clone() { try { return (PostFeedbackResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
7,521
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/Userdata.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Userdata implements Serializable, Cloneable, StructuredPojo { private String email; private String comment; /** * @param email */ public void setEmail(String email) { this.email = email; } /** * @return */ public String getEmail() { return this.email; } /** * @param email * @return Returns a reference to this object so that method calls can be chained together. */ public Userdata email(String email) { setEmail(email); return this; } /** * @param comment */ public void setComment(String comment) { this.comment = comment; } /** * @return */ public String getComment() { return this.comment; } /** * @param comment * @return Returns a reference to this object so that method calls can be chained together. */ public Userdata comment(String comment) { setComment(comment); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getEmail() != null) sb.append("Email: ").append(getEmail()).append(","); if (getComment() != null) sb.append("Comment: ").append(getComment()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Userdata == false) return false; Userdata other = (Userdata) obj; if (other.getEmail() == null ^ this.getEmail() == null) return false; if (other.getEmail() != null && other.getEmail().equals(this.getEmail()) == false) return false; if (other.getComment() == null ^ this.getComment() == null) return false; if (other.getComment() != null && other.getComment().equals(this.getComment()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getEmail() == null) ? 0 : getEmail().hashCode()); hashCode = prime * hashCode + ((getComment() == null) ? 0 : getComment().hashCode()); return hashCode; } @Override public Userdata clone() { try { return (Userdata) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { software.amazon.awssdk.services.toolkittelemetry.model.transform.UserdataMarshaller.getInstance().marshall(this, protocolMarshaller); } }
7,522
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/PostErrorReportResult.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostErrorReportResult extends com.amazonaws.opensdk.BaseResult implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PostErrorReportResult == false) return false; PostErrorReportResult other = (PostErrorReportResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public PostErrorReportResult clone() { try { return (PostErrorReportResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
7,523
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/AWSProduct.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum AWSProduct { Canary("canary"), AWSToolkitForJetBrains("AWS Toolkit For JetBrains"), AWSToolkitForEclipse("AWS Toolkit For Eclipse"), AWSToolkitForVisualStudio("AWS Toolkit For VisualStudio"), AWSToolkitForVSCode("AWS Toolkit For VS Code"); private String value; private AWSProduct(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return AWSProduct corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static AWSProduct fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (AWSProduct enumEntry : AWSProduct.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
7,524
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/PostMetricsResult.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostMetricsResult extends com.amazonaws.opensdk.BaseResult implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PostMetricsResult == false) return false; PostMetricsResult other = (PostMetricsResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public PostMetricsResult clone() { try { return (PostMetricsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
7,525
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/Sentiment.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum Sentiment { Positive("Positive"), Negative("Negative"); private String value; private Sentiment(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return Sentiment corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static Sentiment fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (Sentiment enumEntry : Sentiment.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
7,526
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/PostErrorReportRequest.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.auth.RequestSigner; import com.amazonaws.opensdk.protect.auth.RequestSignerAware; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostErrorReportRequest extends com.amazonaws.opensdk.BaseRequest implements Serializable, Cloneable, RequestSignerAware { private String aWSProduct; private String aWSProductVersion; private java.util.List<MetadataEntry> metadata; private Userdata userdata; private ErrorDetails errorDetails; /** * @param aWSProduct * @see AWSProduct */ public void setAWSProduct(String aWSProduct) { this.aWSProduct = aWSProduct; } /** * @return * @see AWSProduct */ public String getAWSProduct() { return this.aWSProduct; } /** * @param aWSProduct * @return Returns a reference to this object so that method calls can be chained together. * @see AWSProduct */ public PostErrorReportRequest aWSProduct(String aWSProduct) { setAWSProduct(aWSProduct); return this; } /** * @param aWSProduct * @see AWSProduct */ public void setAWSProduct(AWSProduct aWSProduct) { aWSProduct(aWSProduct); } /** * @param aWSProduct * @return Returns a reference to this object so that method calls can be chained together. * @see AWSProduct */ public PostErrorReportRequest aWSProduct(AWSProduct aWSProduct) { this.aWSProduct = aWSProduct.toString(); return this; } /** * @param aWSProductVersion */ public void setAWSProductVersion(String aWSProductVersion) { this.aWSProductVersion = aWSProductVersion; } /** * @return */ public String getAWSProductVersion() { return this.aWSProductVersion; } /** * @param aWSProductVersion * @return Returns a reference to this object so that method calls can be chained together. */ public PostErrorReportRequest aWSProductVersion(String aWSProductVersion) { setAWSProductVersion(aWSProductVersion); return this; } /** * @return */ public java.util.List<MetadataEntry> getMetadata() { return metadata; } /** * @param metadata */ public void setMetadata(java.util.Collection<MetadataEntry> metadata) { if (metadata == null) { this.metadata = null; return; } this.metadata = new java.util.ArrayList<MetadataEntry>(metadata); } /** * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setMetadata(java.util.Collection)} or {@link #withMetadata(java.util.Collection)} if you want to override * the existing values. * </p> * * @param metadata * @return Returns a reference to this object so that method calls can be chained together. */ public PostErrorReportRequest metadata(MetadataEntry... metadata) { if (this.metadata == null) { setMetadata(new java.util.ArrayList<MetadataEntry>(metadata.length)); } for (MetadataEntry ele : metadata) { this.metadata.add(ele); } return this; } /** * @param metadata * @return Returns a reference to this object so that method calls can be chained together. */ public PostErrorReportRequest metadata(java.util.Collection<MetadataEntry> metadata) { setMetadata(metadata); return this; } /** * @param userdata */ public void setUserdata(Userdata userdata) { this.userdata = userdata; } /** * @return */ public Userdata getUserdata() { return this.userdata; } /** * @param userdata * @return Returns a reference to this object so that method calls can be chained together. */ public PostErrorReportRequest userdata(Userdata userdata) { setUserdata(userdata); return this; } /** * @param errorDetails */ public void setErrorDetails(ErrorDetails errorDetails) { this.errorDetails = errorDetails; } /** * @return */ public ErrorDetails getErrorDetails() { return this.errorDetails; } /** * @param errorDetails * @return Returns a reference to this object so that method calls can be chained together. */ public PostErrorReportRequest errorDetails(ErrorDetails errorDetails) { setErrorDetails(errorDetails); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAWSProduct() != null) sb.append("AWSProduct: ").append(getAWSProduct()).append(","); if (getAWSProductVersion() != null) sb.append("AWSProductVersion: ").append(getAWSProductVersion()).append(","); if (getMetadata() != null) sb.append("Metadata: ").append(getMetadata()).append(","); if (getUserdata() != null) sb.append("Userdata: ").append(getUserdata()).append(","); if (getErrorDetails() != null) sb.append("ErrorDetails: ").append(getErrorDetails()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PostErrorReportRequest == false) return false; PostErrorReportRequest other = (PostErrorReportRequest) obj; if (other.getAWSProduct() == null ^ this.getAWSProduct() == null) return false; if (other.getAWSProduct() != null && other.getAWSProduct().equals(this.getAWSProduct()) == false) return false; if (other.getAWSProductVersion() == null ^ this.getAWSProductVersion() == null) return false; if (other.getAWSProductVersion() != null && other.getAWSProductVersion().equals(this.getAWSProductVersion()) == false) return false; if (other.getMetadata() == null ^ this.getMetadata() == null) return false; if (other.getMetadata() != null && other.getMetadata().equals(this.getMetadata()) == false) return false; if (other.getUserdata() == null ^ this.getUserdata() == null) return false; if (other.getUserdata() != null && other.getUserdata().equals(this.getUserdata()) == false) return false; if (other.getErrorDetails() == null ^ this.getErrorDetails() == null) return false; if (other.getErrorDetails() != null && other.getErrorDetails().equals(this.getErrorDetails()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAWSProduct() == null) ? 0 : getAWSProduct().hashCode()); hashCode = prime * hashCode + ((getAWSProductVersion() == null) ? 0 : getAWSProductVersion().hashCode()); hashCode = prime * hashCode + ((getMetadata() == null) ? 0 : getMetadata().hashCode()); hashCode = prime * hashCode + ((getUserdata() == null) ? 0 : getUserdata().hashCode()); hashCode = prime * hashCode + ((getErrorDetails() == null) ? 0 : getErrorDetails().hashCode()); return hashCode; } @Override public PostErrorReportRequest clone() { return (PostErrorReportRequest) super.clone(); } @Override public Class<? extends RequestSigner> signerType() { return com.amazonaws.opensdk.protect.auth.IamRequestSigner.class; } /** * Set the configuration for this request. * * @param sdkRequestConfig * Request configuration. * @return This object for method chaining. */ public PostErrorReportRequest sdkRequestConfig(com.amazonaws.opensdk.SdkRequestConfig sdkRequestConfig) { super.sdkRequestConfig(sdkRequestConfig); return this; } }
7,527
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/MetadataEntry.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MetadataEntry implements Serializable, Cloneable, StructuredPojo { private String key; private String value; /** * @param key */ public void setKey(String key) { this.key = key; } /** * @return */ public String getKey() { return this.key; } /** * @param key * @return Returns a reference to this object so that method calls can be chained together. */ public MetadataEntry key(String key) { setKey(key); return this; } /** * @param value */ public void setValue(String value) { this.value = value; } /** * @return */ public String getValue() { return this.value; } /** * @param value * @return Returns a reference to this object so that method calls can be chained together. */ public MetadataEntry value(String value) { setValue(value); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKey() != null) sb.append("Key: ").append(getKey()).append(","); if (getValue() != null) sb.append("Value: ").append(getValue()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof MetadataEntry == false) return false; MetadataEntry other = (MetadataEntry) obj; if (other.getKey() == null ^ this.getKey() == null) return false; if (other.getKey() != null && other.getKey().equals(this.getKey()) == false) return false; if (other.getValue() == null ^ this.getValue() == null) return false; if (other.getValue() != null && other.getValue().equals(this.getValue()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKey() == null) ? 0 : getKey().hashCode()); hashCode = prime * hashCode + ((getValue() == null) ? 0 : getValue().hashCode()); return hashCode; } @Override public MetadataEntry clone() { try { return (MetadataEntry) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { software.amazon.awssdk.services.toolkittelemetry.model.transform.MetadataEntryMarshaller.getInstance().marshall(this, protocolMarshaller); } }
7,528
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/ErrorDetails.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ErrorDetails implements Serializable, Cloneable, StructuredPojo { private String command; private Long epochTimestamp; private String type; private String message; private String stackTrace; /** * @param command */ public void setCommand(String command) { this.command = command; } /** * @return */ public String getCommand() { return this.command; } /** * @param command * @return Returns a reference to this object so that method calls can be chained together. */ public ErrorDetails command(String command) { setCommand(command); return this; } /** * @param epochTimestamp */ public void setEpochTimestamp(Long epochTimestamp) { this.epochTimestamp = epochTimestamp; } /** * @return */ public Long getEpochTimestamp() { return this.epochTimestamp; } /** * @param epochTimestamp * @return Returns a reference to this object so that method calls can be chained together. */ public ErrorDetails epochTimestamp(Long epochTimestamp) { setEpochTimestamp(epochTimestamp); return this; } /** * @param type */ public void setType(String type) { this.type = type; } /** * @return */ public String getType() { return this.type; } /** * @param type * @return Returns a reference to this object so that method calls can be chained together. */ public ErrorDetails type(String type) { setType(type); return this; } /** * @param message */ public void setMessage(String message) { this.message = message; } /** * @return */ public String getMessage() { return this.message; } /** * @param message * @return Returns a reference to this object so that method calls can be chained together. */ public ErrorDetails message(String message) { setMessage(message); return this; } /** * @param stackTrace */ public void setStackTrace(String stackTrace) { this.stackTrace = stackTrace; } /** * @return */ public String getStackTrace() { return this.stackTrace; } /** * @param stackTrace * @return Returns a reference to this object so that method calls can be chained together. */ public ErrorDetails stackTrace(String stackTrace) { setStackTrace(stackTrace); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCommand() != null) sb.append("Command: ").append(getCommand()).append(","); if (getEpochTimestamp() != null) sb.append("EpochTimestamp: ").append(getEpochTimestamp()).append(","); if (getType() != null) sb.append("Type: ").append(getType()).append(","); if (getMessage() != null) sb.append("Message: ").append(getMessage()).append(","); if (getStackTrace() != null) sb.append("StackTrace: ").append(getStackTrace()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ErrorDetails == false) return false; ErrorDetails other = (ErrorDetails) obj; if (other.getCommand() == null ^ this.getCommand() == null) return false; if (other.getCommand() != null && other.getCommand().equals(this.getCommand()) == false) return false; if (other.getEpochTimestamp() == null ^ this.getEpochTimestamp() == null) return false; if (other.getEpochTimestamp() != null && other.getEpochTimestamp().equals(this.getEpochTimestamp()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getMessage() == null ^ this.getMessage() == null) return false; if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false) return false; if (other.getStackTrace() == null ^ this.getStackTrace() == null) return false; if (other.getStackTrace() != null && other.getStackTrace().equals(this.getStackTrace()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCommand() == null) ? 0 : getCommand().hashCode()); hashCode = prime * hashCode + ((getEpochTimestamp() == null) ? 0 : getEpochTimestamp().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode()); hashCode = prime * hashCode + ((getStackTrace() == null) ? 0 : getStackTrace().hashCode()); return hashCode; } @Override public ErrorDetails clone() { try { return (ErrorDetails) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { software.amazon.awssdk.services.toolkittelemetry.model.transform.ErrorDetailsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
7,529
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/ErrorDetailsJsonUnmarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ErrorDetails JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ErrorDetailsJsonUnmarshaller implements Unmarshaller<ErrorDetails, JsonUnmarshallerContext> { public ErrorDetails unmarshall(JsonUnmarshallerContext context) throws Exception { ErrorDetails errorDetails = new ErrorDetails(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Command", targetDepth)) { context.nextToken(); errorDetails.setCommand(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("EpochTimestamp", targetDepth)) { context.nextToken(); errorDetails.setEpochTimestamp(context.getUnmarshaller(Long.class).unmarshall(context)); } if (context.testExpression("Type", targetDepth)) { context.nextToken(); errorDetails.setType(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Message", targetDepth)) { context.nextToken(); errorDetails.setMessage(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("StackTrace", targetDepth)) { context.nextToken(); errorDetails.setStackTrace(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return errorDetails; } private static ErrorDetailsJsonUnmarshaller instance; public static ErrorDetailsJsonUnmarshaller getInstance() { if (instance == null) instance = new ErrorDetailsJsonUnmarshaller(); return instance; } }
7,530
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/MetricDatumMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * MetricDatumMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class MetricDatumMarshaller { private static final MarshallingInfo<String> METRICNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MetricName").build(); private static final MarshallingInfo<Long> EPOCHTIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.LONG) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EpochTimestamp").build(); private static final MarshallingInfo<String> UNIT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Unit").build(); private static final MarshallingInfo<Double> VALUE_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Value").build(); private static final MarshallingInfo<List> METADATA_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Metadata").build(); private static final MetricDatumMarshaller instance = new MetricDatumMarshaller(); public static MetricDatumMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(MetricDatum metricDatum, ProtocolMarshaller protocolMarshaller) { if (metricDatum == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(metricDatum.getMetricName(), METRICNAME_BINDING); protocolMarshaller.marshall(metricDatum.getEpochTimestamp(), EPOCHTIMESTAMP_BINDING); protocolMarshaller.marshall(metricDatum.getUnit(), UNIT_BINDING); protocolMarshaller.marshall(metricDatum.getValue(), VALUE_BINDING); protocolMarshaller.marshall(metricDatum.getMetadata(), METADATA_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,531
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/PostFeedbackResultJsonUnmarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.*; /** * PostFeedbackResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostFeedbackResultJsonUnmarshaller implements Unmarshaller<PostFeedbackResult, JsonUnmarshallerContext> { public PostFeedbackResult unmarshall(JsonUnmarshallerContext context) throws Exception { PostFeedbackResult postFeedbackResult = new PostFeedbackResult(); return postFeedbackResult; } private static PostFeedbackResultJsonUnmarshaller instance; public static PostFeedbackResultJsonUnmarshaller getInstance() { if (instance == null) instance = new PostFeedbackResultJsonUnmarshaller(); return instance; } }
7,532
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/PostFeedbackRequestMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * PostFeedbackRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PostFeedbackRequestMarshaller { private static final MarshallingInfo<String> AWSPRODUCT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AWSProduct").build(); private static final MarshallingInfo<String> AWSPRODUCTVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AWSProductVersion").build(); private static final MarshallingInfo<String> OS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("OS").build(); private static final MarshallingInfo<String> OSVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("OSVersion").build(); private static final MarshallingInfo<String> PARENTPRODUCT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ParentProduct").build(); private static final MarshallingInfo<String> PARENTPRODUCTVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ParentProductVersion").build(); private static final MarshallingInfo<List> METADATA_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Metadata").build(); private static final MarshallingInfo<String> SENTIMENT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Sentiment").build(); private static final MarshallingInfo<String> COMMENT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Comment").build(); private static final PostFeedbackRequestMarshaller instance = new PostFeedbackRequestMarshaller(); public static PostFeedbackRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(PostFeedbackRequest postFeedbackRequest, ProtocolMarshaller protocolMarshaller) { if (postFeedbackRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(postFeedbackRequest.getAWSProduct(), AWSPRODUCT_BINDING); protocolMarshaller.marshall(postFeedbackRequest.getAWSProductVersion(), AWSPRODUCTVERSION_BINDING); protocolMarshaller.marshall(postFeedbackRequest.getOS(), OS_BINDING); protocolMarshaller.marshall(postFeedbackRequest.getOSVersion(), OSVERSION_BINDING); protocolMarshaller.marshall(postFeedbackRequest.getParentProduct(), PARENTPRODUCT_BINDING); protocolMarshaller.marshall(postFeedbackRequest.getParentProductVersion(), PARENTPRODUCTVERSION_BINDING); protocolMarshaller.marshall(postFeedbackRequest.getMetadata(), METADATA_BINDING); protocolMarshaller.marshall(postFeedbackRequest.getSentiment(), SENTIMENT_BINDING); protocolMarshaller.marshall(postFeedbackRequest.getComment(), COMMENT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,533
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/UserdataJsonUnmarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * Userdata JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UserdataJsonUnmarshaller implements Unmarshaller<Userdata, JsonUnmarshallerContext> { public Userdata unmarshall(JsonUnmarshallerContext context) throws Exception { Userdata userdata = new Userdata(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Email", targetDepth)) { context.nextToken(); userdata.setEmail(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Comment", targetDepth)) { context.nextToken(); userdata.setComment(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return userdata; } private static UserdataJsonUnmarshaller instance; public static UserdataJsonUnmarshaller getInstance() { if (instance == null) instance = new UserdataJsonUnmarshaller(); return instance; } }
7,534
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/PostErrorReportRequestProtocolMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * PostErrorReportRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PostErrorReportRequestProtocolMarshaller implements Marshaller<Request<PostErrorReportRequest>, PostErrorReportRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.API_GATEWAY).requestUri("/errorReport") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).serviceName("TelemetryClient").build(); private final com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl protocolFactory; public PostErrorReportRequestProtocolMarshaller(com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl protocolFactory) { this.protocolFactory = protocolFactory; } public Request<PostErrorReportRequest> marshall(PostErrorReportRequest postErrorReportRequest) { if (postErrorReportRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<PostErrorReportRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, postErrorReportRequest); protocolMarshaller.startMarshalling(); PostErrorReportRequestMarshaller.getInstance().marshall(postErrorReportRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,535
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/PostMetricsRequestProtocolMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * PostMetricsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PostMetricsRequestProtocolMarshaller implements Marshaller<Request<PostMetricsRequest>, PostMetricsRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.API_GATEWAY).requestUri("/metrics") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).serviceName("TelemetryClient").build(); private final com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl protocolFactory; public PostMetricsRequestProtocolMarshaller(com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl protocolFactory) { this.protocolFactory = protocolFactory; } public Request<PostMetricsRequest> marshall(PostMetricsRequest postMetricsRequest) { if (postMetricsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<PostMetricsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, postMetricsRequest); protocolMarshaller.startMarshalling(); PostMetricsRequestMarshaller.getInstance().marshall(postMetricsRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,536
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/MetadataEntryJsonUnmarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * MetadataEntry JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MetadataEntryJsonUnmarshaller implements Unmarshaller<MetadataEntry, JsonUnmarshallerContext> { public MetadataEntry unmarshall(JsonUnmarshallerContext context) throws Exception { MetadataEntry metadataEntry = new MetadataEntry(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Key", targetDepth)) { context.nextToken(); metadataEntry.setKey(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Value", targetDepth)) { context.nextToken(); metadataEntry.setValue(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return metadataEntry; } private static MetadataEntryJsonUnmarshaller instance; public static MetadataEntryJsonUnmarshaller getInstance() { if (instance == null) instance = new MetadataEntryJsonUnmarshaller(); return instance; } }
7,537
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/MetadataEntryMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * MetadataEntryMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class MetadataEntryMarshaller { private static final MarshallingInfo<String> KEY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Key").build(); private static final MarshallingInfo<String> VALUE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Value").build(); private static final MetadataEntryMarshaller instance = new MetadataEntryMarshaller(); public static MetadataEntryMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(MetadataEntry metadataEntry, ProtocolMarshaller protocolMarshaller) { if (metadataEntry == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(metadataEntry.getKey(), KEY_BINDING); protocolMarshaller.marshall(metadataEntry.getValue(), VALUE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,538
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/PostErrorReportRequestMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * PostErrorReportRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PostErrorReportRequestMarshaller { private static final MarshallingInfo<String> AWSPRODUCT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AWSProduct").build(); private static final MarshallingInfo<String> AWSPRODUCTVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AWSProductVersion").build(); private static final MarshallingInfo<List> METADATA_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Metadata").build(); private static final MarshallingInfo<StructuredPojo> USERDATA_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Userdata").build(); private static final MarshallingInfo<StructuredPojo> ERRORDETAILS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ErrorDetails").build(); private static final PostErrorReportRequestMarshaller instance = new PostErrorReportRequestMarshaller(); public static PostErrorReportRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(PostErrorReportRequest postErrorReportRequest, ProtocolMarshaller protocolMarshaller) { if (postErrorReportRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(postErrorReportRequest.getAWSProduct(), AWSPRODUCT_BINDING); protocolMarshaller.marshall(postErrorReportRequest.getAWSProductVersion(), AWSPRODUCTVERSION_BINDING); protocolMarshaller.marshall(postErrorReportRequest.getMetadata(), METADATA_BINDING); protocolMarshaller.marshall(postErrorReportRequest.getUserdata(), USERDATA_BINDING); protocolMarshaller.marshall(postErrorReportRequest.getErrorDetails(), ERRORDETAILS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,539
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/MetricDatumJsonUnmarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * MetricDatum JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MetricDatumJsonUnmarshaller implements Unmarshaller<MetricDatum, JsonUnmarshallerContext> { public MetricDatum unmarshall(JsonUnmarshallerContext context) throws Exception { MetricDatum metricDatum = new MetricDatum(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("MetricName", targetDepth)) { context.nextToken(); metricDatum.setMetricName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("EpochTimestamp", targetDepth)) { context.nextToken(); metricDatum.setEpochTimestamp(context.getUnmarshaller(Long.class).unmarshall(context)); } if (context.testExpression("Unit", targetDepth)) { context.nextToken(); metricDatum.setUnit(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Value", targetDepth)) { context.nextToken(); metricDatum.setValue(context.getUnmarshaller(Double.class).unmarshall(context)); } if (context.testExpression("Metadata", targetDepth)) { context.nextToken(); metricDatum.setMetadata(new ListUnmarshaller<MetadataEntry>(MetadataEntryJsonUnmarshaller.getInstance()).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return metricDatum; } private static MetricDatumJsonUnmarshaller instance; public static MetricDatumJsonUnmarshaller getInstance() { if (instance == null) instance = new MetricDatumJsonUnmarshaller(); return instance; } }
7,540
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/ErrorDetailsMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ErrorDetailsMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ErrorDetailsMarshaller { private static final MarshallingInfo<String> COMMAND_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Command").build(); private static final MarshallingInfo<Long> EPOCHTIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.LONG) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EpochTimestamp").build(); private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Type").build(); private static final MarshallingInfo<String> MESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Message").build(); private static final MarshallingInfo<String> STACKTRACE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("StackTrace").build(); private static final ErrorDetailsMarshaller instance = new ErrorDetailsMarshaller(); public static ErrorDetailsMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ErrorDetails errorDetails, ProtocolMarshaller protocolMarshaller) { if (errorDetails == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(errorDetails.getCommand(), COMMAND_BINDING); protocolMarshaller.marshall(errorDetails.getEpochTimestamp(), EPOCHTIMESTAMP_BINDING); protocolMarshaller.marshall(errorDetails.getType(), TYPE_BINDING); protocolMarshaller.marshall(errorDetails.getMessage(), MESSAGE_BINDING); protocolMarshaller.marshall(errorDetails.getStackTrace(), STACKTRACE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,541
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/PostFeedbackRequestProtocolMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * PostFeedbackRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PostFeedbackRequestProtocolMarshaller implements Marshaller<Request<PostFeedbackRequest>, PostFeedbackRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.API_GATEWAY).requestUri("/feedback") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).serviceName("TelemetryClient").build(); private final com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl protocolFactory; public PostFeedbackRequestProtocolMarshaller(com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl protocolFactory) { this.protocolFactory = protocolFactory; } public Request<PostFeedbackRequest> marshall(PostFeedbackRequest postFeedbackRequest) { if (postFeedbackRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<PostFeedbackRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, postFeedbackRequest); protocolMarshaller.startMarshalling(); PostFeedbackRequestMarshaller.getInstance().marshall(postFeedbackRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,542
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/UserdataMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UserdataMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UserdataMarshaller { private static final MarshallingInfo<String> EMAIL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Email").build(); private static final MarshallingInfo<String> COMMENT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Comment").build(); private static final UserdataMarshaller instance = new UserdataMarshaller(); public static UserdataMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(Userdata userdata, ProtocolMarshaller protocolMarshaller) { if (userdata == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(userdata.getEmail(), EMAIL_BINDING); protocolMarshaller.marshall(userdata.getComment(), COMMENT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,543
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/PostMetricsRequestMarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * PostMetricsRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PostMetricsRequestMarshaller { private static final MarshallingInfo<String> AWSPRODUCT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AWSProduct").build(); private static final MarshallingInfo<String> AWSPRODUCTVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AWSProductVersion").build(); private static final MarshallingInfo<String> CLIENTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("ClientID").build(); private static final MarshallingInfo<String> OS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("OS").build(); private static final MarshallingInfo<String> OSVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("OSVersion").build(); private static final MarshallingInfo<String> PARENTPRODUCT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ParentProduct").build(); private static final MarshallingInfo<String> PARENTPRODUCTVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ParentProductVersion").build(); private static final MarshallingInfo<List> METRICDATA_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("MetricData").build(); private static final PostMetricsRequestMarshaller instance = new PostMetricsRequestMarshaller(); public static PostMetricsRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(PostMetricsRequest postMetricsRequest, ProtocolMarshaller protocolMarshaller) { if (postMetricsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(postMetricsRequest.getAWSProduct(), AWSPRODUCT_BINDING); protocolMarshaller.marshall(postMetricsRequest.getAWSProductVersion(), AWSPRODUCTVERSION_BINDING); protocolMarshaller.marshall(postMetricsRequest.getClientID(), CLIENTID_BINDING); protocolMarshaller.marshall(postMetricsRequest.getOS(), OS_BINDING); protocolMarshaller.marshall(postMetricsRequest.getOSVersion(), OSVERSION_BINDING); protocolMarshaller.marshall(postMetricsRequest.getParentProduct(), PARENTPRODUCT_BINDING); protocolMarshaller.marshall(postMetricsRequest.getParentProductVersion(), PARENTPRODUCTVERSION_BINDING); protocolMarshaller.marshall(postMetricsRequest.getMetricData(), METRICDATA_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
7,544
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/PostErrorReportResultJsonUnmarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.*; /** * PostErrorReportResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostErrorReportResultJsonUnmarshaller implements Unmarshaller<PostErrorReportResult, JsonUnmarshallerContext> { public PostErrorReportResult unmarshall(JsonUnmarshallerContext context) throws Exception { PostErrorReportResult postErrorReportResult = new PostErrorReportResult(); return postErrorReportResult; } private static PostErrorReportResultJsonUnmarshaller instance; public static PostErrorReportResultJsonUnmarshaller getInstance() { if (instance == null) instance = new PostErrorReportResultJsonUnmarshaller(); return instance; } }
7,545
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/software/amazon/awssdk/services/toolkittelemetry/model/transform/PostMetricsResultJsonUnmarshaller.java
/* * Copyright 2015-2020 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 software.amazon.awssdk.services.toolkittelemetry.model.transform; import javax.annotation.Generated; import software.amazon.awssdk.services.toolkittelemetry.model.*; import com.amazonaws.transform.*; /** * PostMetricsResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostMetricsResultJsonUnmarshaller implements Unmarshaller<PostMetricsResult, JsonUnmarshallerContext> { public PostMetricsResult unmarshall(JsonUnmarshallerContext context) throws Exception { PostMetricsResult postMetricsResult = new PostMetricsResult(); return postMetricsResult; } private static PostMetricsResultJsonUnmarshaller instance; public static PostMetricsResultJsonUnmarshaller getInstance() { if (instance == null) instance = new PostMetricsResultJsonUnmarshaller(); return instance; } }
7,546
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/AwsToolkitCore.java
/* * Copyright 2010-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.ErrorSupportProvider; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.util.Policy; import org.osgi.framework.BundleContext; import org.osgi.util.tracker.ServiceTracker; import com.amazonaws.eclipse.core.accounts.AccountInfoProvider; import com.amazonaws.eclipse.core.accounts.AwsPluginAccountManager; import com.amazonaws.eclipse.core.diagnostic.ui.AwsToolkitErrorSupportProvider; import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.eclipse.core.preferences.PreferencePropertyChangeListener; import com.amazonaws.eclipse.core.preferences.regions.DefaultRegionMonitor; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.telemetry.ClientContextConfig; import com.amazonaws.eclipse.core.telemetry.ToolkitAnalyticsManager; import com.amazonaws.eclipse.core.telemetry.cognito.AWSCognitoCredentialsProvider; import com.amazonaws.eclipse.core.telemetry.internal.NoOpToolkitAnalyticsManager; import com.amazonaws.eclipse.core.telemetry.internal.ToolkitAnalyticsManagerImpl; import com.amazonaws.eclipse.core.ui.preferences.accounts.LegacyPreferenceStoreAccountMerger; import com.amazonaws.eclipse.core.ui.setupwizard.InitialSetupUtils; /** * Entry point for functionality provided by the AWS Toolkit Core plugin, * including access to AWS account information. */ public class AwsToolkitCore extends AbstractAwsPlugin { /** * The singleton instance of this plugin. * <p> * This static field will remain null until doBasicInit() is completed. * * @see #doBasicInit(BundleContext) * @see #getDefault() */ private static AwsToolkitCore plugin = null; /** * Used for blocking method calls of getDefault() before the plugin instance * finishes basic initialization. */ private static final CountDownLatch pluginBasicInitLatch = new CountDownLatch(1); /** * Used for blocking any method calls that requires the full initialization * of the plugin. (e.g. getAccountManager() method requires loading the * profile credentials from the file-system in advance). */ private static final CountDownLatch pluginFullInitLatch = new CountDownLatch(1); // In seconds private static final int BASIC_INIT_MAX_WAIT_TIME = 60; private static final int FULL_INIT_MAX_WAIT_TIME = 60; /** The ID of the main AWS Toolkit preference page */ public static final String ACCOUNT_PREFERENCE_PAGE_ID = "com.amazonaws.eclipse.core.ui.preferences.AwsAccountPreferencePage"; /** The ID of the AWS Toolkit Overview extension point */ public static final String OVERVIEW_EXTENSION_ID = "com.amazonaws.eclipse.core.overview"; /** The ID of the AWS Toolkit Overview editor */ public static final String OVERVIEW_EDITOR_ID = "com.amazonaws.eclipse.core.ui.overview"; /** The ID of the AWS Explorer view */ public static final String EXPLORER_VIEW_ID = "com.amazonaws.eclipse.explorer.view"; public static final String IMAGE_CLOUDFORMATION_SERVICE = "cloudformation-service"; public static final String IMAGE_CLOUDFRONT_SERVICE = "cloudfront-service"; public static final String IMAGE_IAM_SERVICE = "iam-service"; public static final String IMAGE_RDS_SERVICE = "rds-service"; public static final String IMAGE_S3_SERVICE = "s3-service"; public static final String IMAGE_SIMPLEDB_SERVICE = "simpledb-service"; public static final String IMAGE_SNS_SERVICE = "sns-service"; public static final String IMAGE_SQS_SERVICE = "sqs-service"; public static final String IMAGE_REMOVE = "remove"; public static final String IMAGE_ADD = "add"; public static final String IMAGE_EDIT = "edit"; public static final String IMAGE_SAVE = "save"; public static final String IMAGE_AWS_TOOLKIT_TITLE = "aws-toolkit-title"; public static final String IMAGE_EXTERNAL_LINK = "external-link"; public static final String IMAGE_WRENCH = "wrench"; public static final String IMAGE_SCROLL = "scroll"; public static final String IMAGE_GEARS = "gears"; public static final String IMAGE_GEAR = "gear"; public static final String IMAGE_HTML_DOC = "html"; public static final String IMAGE_AWS_LOGO = "logo"; public static final String IMAGE_AWS_ICON = "icon"; public static final String IMAGE_TABLE = "table"; public static final String IMAGE_BUCKET = "bucket"; public static final String IMAGE_REFRESH = "refresh"; public static final String IMAGE_DATABASE = "database"; public static final String IMAGE_STACK = "stack"; public static final String IMAGE_QUEUE = "queue"; public static final String IMAGE_TOPIC = "topic"; public static final String IMAGE_START = "start"; public static final String IMAGE_PUBLISH = "publish"; public static final String IMAGE_EXPORT = "export"; public static final String IMAGE_STREAMING_DISTRIBUTION = "streaming-distribution"; public static final String IMAGE_DISTRIBUTION = "distribution"; public static final String IMAGE_GREEN_CIRCLE = "red-circle"; public static final String IMAGE_RED_CIRCLE = "green-circle"; public static final String IMAGE_GREY_CIRCLE = "grey-circle"; public static final String IMAGE_USER = "user"; public static final String IMAGE_GROUP = "group"; public static final String IMAGE_KEY = "key"; public static final String IMAGE_ROLE = "role"; public static final String IMAGE_INFORMATION = "information"; public static final String IMAGE_DOWNLOAD = "download"; public static final String IMAGE_FLAG_PREFIX = "flag-"; public static final String IMAGE_WIZARD_CONFIGURE_DATABASE = "configure-database-wizard"; /** * Client factories for each individual account in use by the customer. */ private final Map<String, AWSClientFactory> clientsFactoryByAccountId = new HashMap<>(); /** OSGI ServiceTracker object for querying details of proxy configuration */ @SuppressWarnings("rawtypes") private ServiceTracker proxyServiceTracker; /** Monitors for changes of default region */ private DefaultRegionMonitor defaultRegionMonitor; /** * The AccountManager which persists account-related preference properties. * This field is only available after the plugin is fully initialized. */ private AwsPluginAccountManager accountManager; /** * For tracking toolkit analytic sessions and events. */ private ToolkitAnalyticsManager toolkitAnalyticsManager; /* * ====================================== * APIs that require basic initialization * ====================================== */ /** * Returns the singleton instance of this plugin. * <p> * This method will be blocked if the singleton instance has not finished * the basic initialization. * * @return The singleton instance of this plugin. */ public static AwsToolkitCore getDefault() { if (plugin != null) return plugin; try { pluginBasicInitLatch.await(BASIC_INIT_MAX_WAIT_TIME, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new IllegalStateException( "Interrupted while waiting for the AWS toolkit core plugin to initialize", e); } synchronized (AwsToolkitCore.class) { if (plugin == null) { throw new IllegalStateException( "The core plugin is not initialized after waiting for " + BASIC_INIT_MAX_WAIT_TIME + " seconds."); } return plugin; } } /** * Registers a listener to receive notifications when the default * region is changed. * * @param listener * The listener to add. */ public void addDefaultRegionChangeListener(PreferencePropertyChangeListener listener) { defaultRegionMonitor.addChangeListener(listener); } /** * Stops a listener from receiving notifications when the default * region is changed. * * @param listener * The listener to remove. */ public void removeDefaultRegionChangeListener(PreferencePropertyChangeListener listener) { defaultRegionMonitor.removeChangeListener(listener); } /** * Returns the IProxyService that allows callers to * access information on how the proxy is currently * configured. * * @return An IProxyService object that allows callers to * query proxy configuration information. */ public IProxyService getProxyService() { return (IProxyService)proxyServiceTracker.getService(); } /* * ====================================== * APIs that require full initialization * ====================================== */ /** * Returns the client factory. * * This method will be blocked until the singleton instance of the plugin is * fully initialized. */ public static AWSClientFactory getClientFactory() { return getClientFactory(null); } /** * Returns the client factory for the given account id. The client is * responsible for ensuring that the given account Id is valid and properly * configured. * This method will be blocked until the singleton instance of the plugin is * fully initialized. * * @param accountId * The account to use for credentials, or null for the currently * selected account. * @see AwsToolkitCore#getAccountInfo(String) */ public static AWSClientFactory getClientFactory(String accountId) { return getDefault().privateGetClientFactory(accountId); } private synchronized AWSClientFactory privateGetClientFactory(String accountId) { waitTillFullInit(); if ( accountId == null ) accountId = getCurrentAccountId(); if ( !clientsFactoryByAccountId.containsKey(accountId) ) { clientsFactoryByAccountId.put( accountId, // AWSClientFactory uses the accountId to retrieve the credentials new AWSClientFactory(accountId)); } return clientsFactoryByAccountId.get(accountId); } /** * Returns the account manager associated with this plugin. * * This method will be blocked until the plugin is fully initialized. */ public AwsPluginAccountManager getAccountManager() { waitTillFullInit(); return accountManager; } /** * Returns the current account Id * This method will be blocked until the plugin is fully initialized. * */ public String getCurrentAccountId() { waitTillFullInit(); return accountManager.getCurrentAccountId(); } /** * Returns the currently selected account info. * This method will be blocked until the plugin is fully initialized. * * @return The user's AWS account info. */ public AccountInfo getAccountInfo() { waitTillFullInit(); return accountManager.getAccountInfo(); } /** * Returns the toolkit analytics manager. This method blocks until the * plugin is fully initialized and it is guaranteed to return a non-null * value. */ public ToolkitAnalyticsManager getAnalyticsManager() { waitTillFullInit(); return toolkitAnalyticsManager; } /* * ====================================== * Core plugin start-up workflow * ====================================== */ /** * We need to avoid any potentially blocking operations in this method, as * the documentation has explicitly called out: * <p> * This method is intended to perform simple initialization of the plug-in * environment. The platform may terminate initializers that do not complete * in a timely fashion. * * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ @Override public void start(final BundleContext context) throws Exception { super.start(context); long startTime = System.currentTimeMillis(); logInfo("Starting the AWS toolkit core plugin..."); // Publish the "global" plugin singleton immediately after the basic // initialization is done. doBasicInit(context); synchronized (AwsToolkitCore.class) { plugin = this; } pluginBasicInitLatch.countDown(); // Then do full initialization doFullInit(context); pluginFullInitLatch.countDown(); // All other expensive initialization tasks are executed // asynchronously (after all the plugins are started) new Job("Initaliazing AWS toolkit core plugin...") { @Override protected IStatus run(IProgressMonitor monitor) { afterFullInit(context, monitor); return Status.OK_STATUS; } }.schedule(); logInfo(String.format( "AWS toolkit core plugin initialized after %d milliseconds.", System.currentTimeMillis() - startTime)); } /** * Any basic initialization workflow required prior to publishing the plugin * instance via getDefault(). */ @SuppressWarnings({ "rawtypes", "unchecked" }) private void doBasicInit(BundleContext context) { try { registerCustomErrorSupport(); // Initialize proxy tracker proxyServiceTracker = new ServiceTracker(context, IProxyService.class.getName(), null); proxyServiceTracker.open(); } catch (Exception e) { reportException("Internal error when starting the AWS Toolkit plugin.", e); } } /** * The singleton plugin instance will be available via getDeault() BEFORE * this method is executed, but methods that are protected by * waitTillFullInit() will be blocked until this job is completed. */ private void doFullInit(BundleContext context) { try { // Initialize region metadata RegionUtils.init(); // Initialize AccountManager AccountInfoProvider accountInfoProvider = new AccountInfoProvider( getPreferenceStore()); // Load profile credentials. Do not bootstrap credentials file // if it still doesn't exist, and do not show warning if it fails to // load accountInfoProvider.refreshProfileAccountInfo(false, false); accountManager = new AwsPluginAccountManager( getPreferenceStore(), accountInfoProvider); // start monitoring account preference changes accountManager.startAccountMonitors(); // start monitoring the location and content of the credentials file accountManager.startCredentialsFileMonitor(); // Start listening for region preference changes... defaultRegionMonitor = new DefaultRegionMonitor(); getPreferenceStore().addPropertyChangeListener(defaultRegionMonitor); // Start listening to changes on default region and region default account preference, // and correspondingly update current account PreferencePropertyChangeListener resetAccountListenr = new PreferencePropertyChangeListener() { @Override public void watchedPropertyChanged() { Region newRegion = RegionUtils.getCurrentRegion(); accountManager.updateCurrentAccount(newRegion); } }; accountManager.addDefaultAccountChangeListener(resetAccountListenr); addDefaultRegionChangeListener(resetAccountListenr); // Initialize Telemetry toolkitAnalyticsManager = initializeToolkitAnalyticsManager(); toolkitAnalyticsManager.startSession(accountManager, true); } catch (Exception e) { reportException("Internal error when starting the AWS Toolkit plugin.", e); } } /** * Any tasks that don't necessarily need to be run before the plugin starts * will be executed asynchronoulsy. */ private void afterFullInit(BundleContext context, IProgressMonitor monitor) { // Merge legacy preference store based accounts try { LegacyPreferenceStoreAccountMerger .mergeLegacyAccountsIntoCredentialsFile(); accountManager.getAccountInfoProvider() .refreshProfileAccountInfo(false, false); } catch (Exception e) { reportException("Internal error when scanning legacy AWS account configuration.", e); } // Initial setup wizard for account and analytics configuration try { InitialSetupUtils.runInitialSetupWizard(); } catch (Exception e) { reportException( "Internal error when running intial setup wizard.", e); } } /** * This method blocks any method invocation that requires the full * initialization of this plugin instance. */ private void waitTillFullInit() { try { boolean initComplete = pluginFullInitLatch .await(FULL_INIT_MAX_WAIT_TIME, TimeUnit.SECONDS); if ( !initComplete ) { throw new IllegalStateException( "The AWS toolkit core plugin didn't " + "finish initialization after " + FULL_INIT_MAX_WAIT_TIME + " seconds."); } } catch (InterruptedException e) { throw new IllegalStateException( "Interrupted while waiting for the AWS " + "toolkit core plugin to finish initialization.", e); } } /** * Register the custom error-support provider, which provides additional UIs * for users to directly report errors to "aws-eclipse-errors@amazon.com". */ private static void registerCustomErrorSupport() { ErrorSupportProvider existingProvider = Policy.getErrorSupportProvider(); // Keep a reference to the previously configured provider AwsToolkitErrorSupportProvider awsProvider = new AwsToolkitErrorSupportProvider( existingProvider); Policy.setErrorSupportProvider(awsProvider); } public boolean isDebugMode() { return getBundleVersion().contains("qualifier"); } private ToolkitAnalyticsManager initializeToolkitAnalyticsManager() { boolean enabled = getPreferenceStore().getBoolean( PreferenceConstants.P_TOOLKIT_ANALYTICS_COLLECTION_ENABLED); ToolkitAnalyticsManager toReturn = null; if (enabled) { try { if (isDebugMode()) { toReturn = new ToolkitAnalyticsManagerImpl( AWSCognitoCredentialsProvider.TEST_PROVIDER, ClientContextConfig.TEST_CONFIG); } else { toReturn = new ToolkitAnalyticsManagerImpl( AWSCognitoCredentialsProvider.V2_PROVIDER, ClientContextConfig.PROD_CONFIG); } } catch (Exception e) { logError("Failed to initialize analytics manager", e); } } else { logInfo("Toolkit analytics collection disabled"); } if (toReturn == null) { toReturn = new NoOpToolkitAnalyticsManager(); } return toReturn; } /* (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { toolkitAnalyticsManager.endSession(true); accountManager.stopAccountMonitors(); getPreferenceStore().removePropertyChangeListener(defaultRegionMonitor); proxyServiceTracker.close(); plugin = null; super.stop(context); } /* (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#createImageRegistry() */ @Override protected ImageRegistry createImageRegistry() { String[] images = new String[] { IMAGE_WIZARD_CONFIGURE_DATABASE, "/icons/wizards/configure_database.png", IMAGE_CLOUDFORMATION_SERVICE, "/icons/cloudformation-service.png", IMAGE_CLOUDFRONT_SERVICE, "/icons/cloudfront-service.png", IMAGE_IAM_SERVICE, "/icons/iam-service.png", IMAGE_RDS_SERVICE, "/icons/rds-service.png", IMAGE_S3_SERVICE, "/icons/s3-service.png", IMAGE_SIMPLEDB_SERVICE, "/icons/simpledb-service.png", IMAGE_SNS_SERVICE, "/icons/sns-service.png", IMAGE_SQS_SERVICE, "/icons/sqs-service.png", IMAGE_ADD, "/icons/add.png", IMAGE_REMOVE, "/icons/remove.gif", IMAGE_EDIT, "/icons/edit.png", IMAGE_SAVE, "/icons/save.png", IMAGE_REFRESH, "/icons/refresh.png", IMAGE_BUCKET, "/icons/bucket.png", IMAGE_AWS_LOGO, "/icons/logo_aws.png", IMAGE_HTML_DOC, "/icons/document_text.png", IMAGE_GEAR, "/icons/gear.png", IMAGE_GEARS, "/icons/gears.png", IMAGE_SCROLL, "/icons/scroll.png", IMAGE_WRENCH, "/icons/wrench.png", IMAGE_AWS_TOOLKIT_TITLE, "/icons/aws-toolkit-title.png", IMAGE_EXTERNAL_LINK, "/icons/icon_offsite.gif", IMAGE_AWS_ICON, "/icons/aws-box.gif", IMAGE_PUBLISH, "/icons/document_into.png", IMAGE_TABLE, "/icons/table.gif", IMAGE_DATABASE, "/icons/database.png", IMAGE_QUEUE, "/icons/index.png", IMAGE_TOPIC, "/icons/sns_topic.png", IMAGE_START, "/icons/start.png", IMAGE_EXPORT, "/icons/export.gif", IMAGE_STREAMING_DISTRIBUTION, "/icons/streaming-distribution.png", IMAGE_DISTRIBUTION, "/icons/distribution.png", IMAGE_GREEN_CIRCLE, "/icons/green-circle.png", IMAGE_GREY_CIRCLE, "/icons/grey-circle.png", IMAGE_RED_CIRCLE, "/icons/red-circle.png", IMAGE_USER, "/icons/user.png", IMAGE_GROUP, "/icons/group.png", IMAGE_KEY, "/icons/key.png", IMAGE_ROLE, "/icons/role.png", IMAGE_INFORMATION, "/icons/information.png", IMAGE_DOWNLOAD, "/icons/download.png", IMAGE_STACK, "/icons/stack.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; } }
7,547
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/HttpClientFactory.java
/* * Copyright 2014 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core; import java.net.URI; import java.net.URISyntaxException; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.NTCredentials; import org.apache.http.impl.client.BasicCredentialsProvider; import org.eclipse.core.net.proxy.IProxyData; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.core.runtime.Plugin; import org.eclipse.jface.preference.IPreferenceStore; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; /** * An HttpClient factory that sets up timeouts and proxy settings. You should * never create an HttpClient of your own, you should always use this factory. */ public final class HttpClientFactory { public static AwsToolkitHttpClient create(Plugin plugin, String url) { IPreferenceStore preferences = AwsToolkitCore.getDefault().getPreferenceStore(); int connectionTimeout = preferences.getInt(PreferenceConstants.P_CONNECTION_TIMEOUT); int socketTimeout = preferences.getInt(PreferenceConstants.P_SOCKET_TIMEOUT); IProxyData data = getEclipseProxyData(url); HttpHost httpHost = null; BasicCredentialsProvider credentialsProvider = null; if (data != null) { httpHost = new HttpHost(data.getHost(), data.getPort()); if (data.isRequiresAuthentication()) { credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(httpHost), new NTCredentials(data.getUserId(), data.getPassword(), null, null)); } } return AwsToolkitHttpClient.builder() .setConnectionTimeout(connectionTimeout) .setSocketTimeout(socketTimeout) .setUserAgent(AwsClientUtils.formatUserAgentString("AWS-Toolkit-For-Eclipse", plugin)) .setProxy(httpHost) .setCredentialsProvider(credentialsProvider) .build(); } private static IProxyData getEclipseProxyData(String url) { AwsToolkitCore plugin = AwsToolkitCore.getDefault(); if (plugin != null) { IProxyService proxyService = AwsToolkitCore.getDefault().getProxyService(); if (proxyService.isProxiesEnabled()) { try { IProxyData[] proxyData = proxyService.select(new URI(url)); if (proxyData.length > 0) { return proxyData[0]; } } catch (URISyntaxException e) { plugin.logError(e.getMessage(), e); } } } return null; } private HttpClientFactory() { } }
7,548
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/AccountAndRegionChangeListener.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core; import com.amazonaws.eclipse.core.accounts.AccountInfoChangeListener; import com.amazonaws.eclipse.core.preferences.PreferencePropertyChangeListener; /** * An abstract implementation of the AccountInfoChangeListener and the * PreferencePropertyChangeListener. Refreshable views in the toolkit can * re-used this class to specify its behavior when the user changes its default * account or region. */ public abstract class AccountAndRegionChangeListener implements AccountInfoChangeListener, PreferencePropertyChangeListener{ @Override public void watchedPropertyChanged() { onAccountOrRegionChange(); } @Override public void onAccountInfoChange() { onAccountOrRegionChange(); } public abstract void onAccountOrRegionChange(); }
7,549
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/AwsToolkitHttpClient.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig.Builder; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; public class AwsToolkitHttpClient { private final HttpClient httpClient; private AwsToolkitHttpClient( Integer connectionTimeout, Integer socketTimeout, String userAgent, HttpHost proxy, CredentialsProvider credentialsProvider) { Builder requestConfigBuilder = RequestConfig.custom(); if (connectionTimeout != null) { requestConfigBuilder.setConnectionRequestTimeout(connectionTimeout); } if (socketTimeout != null) { requestConfigBuilder.setSocketTimeout(socketTimeout); } HttpClientBuilder builder = HttpClientBuilder.create() .setDefaultRequestConfig(requestConfigBuilder.build()) .setUserAgent(userAgent); if (proxy != null) { builder.setProxy(proxy); if (credentialsProvider != null) { builder.setDefaultCredentialsProvider(credentialsProvider); } } httpClient = builder .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) .build(); } /** * Head the given URL for the last modified date. * * @param url The target URL resource. * @return The last modified date give the URL, or null if the date cannot be retrieved * @throws ClientProtocolException * @throws IOException */ public Date getLastModifiedDate(String url) throws ClientProtocolException, IOException { HttpHead headMethod = new HttpHead(url); HttpResponse response = httpClient.execute(headMethod); Header header = response.getFirstHeader("Last-Modified"); if (header != null) { String lastModifiedDateString = header.getValue(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); try { return dateFormat.parse(lastModifiedDateString); } catch (ParseException e) { return null; } } return null; } /** * Fetch the content of the target URL and redirect to the output stream. * If no content is fetched, do nothing. * * @param url The target URL * @param output The OutputStream * @throws ClientProtocolException * @throws IOException */ public void outputEntityContent(String url, OutputStream output) throws ClientProtocolException, IOException { try (InputStream inputStream = getEntityContent(url)) { if (inputStream == null) { return; } int length; byte[] buffer = new byte[2048]; while ((length = inputStream.read(buffer)) != -1) { output.write(buffer, 0, length); } } } /** * Return the input stream of the underlying resource in the target URL. * @param url The target URL * @return The underlying input stream, or null if it doesn't have entity * @throws ClientProtocolException * @throws IOException */ public InputStream getEntityContent(String url) throws ClientProtocolException, IOException { HttpGet getMethod = new HttpGet(url); HttpResponse response = httpClient.execute(getMethod); HttpEntity entity = response.getEntity(); return entity == null ? null : entity.getContent(); } static AwsToolkitHttpClientBuilder builder() { return new AwsToolkitHttpClientBuilder(); } static final class AwsToolkitHttpClientBuilder { private Integer connectionTimeout; private Integer socketTimeout; private String userAgent; private HttpHost proxy; private CredentialsProvider credentialsProvider; private AwsToolkitHttpClientBuilder() {} public AwsToolkitHttpClient build() { return new AwsToolkitHttpClient(connectionTimeout, socketTimeout, userAgent, proxy, credentialsProvider); } public Integer getConnectionTimeout() { return connectionTimeout; } public AwsToolkitHttpClientBuilder setConnectionTimeout(Integer connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public Integer getSocketTimeout() { return socketTimeout; } public AwsToolkitHttpClientBuilder setSocketTimeout(Integer socketTimeout) { this.socketTimeout = socketTimeout; return this; } public String getUserAgent() { return userAgent; } public AwsToolkitHttpClientBuilder setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } public HttpHost getProxy() { return proxy; } public AwsToolkitHttpClientBuilder setProxy(HttpHost proxy) { this.proxy = proxy; return this; } public CredentialsProvider getCredentialsProvider() { return credentialsProvider; } public AwsToolkitHttpClientBuilder setCredentialsProvider(CredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; } } }
7,550
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/AWSClientFactory.java
/* * Copyright 2010-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.eclipse.core.net.proxy.IProxyChangeEvent; import org.eclipse.core.net.proxy.IProxyData; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.jface.preference.IPreferenceStore; import com.amazonaws.AmazonWebServiceClient; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.AnonymousAWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; import com.amazonaws.client.builder.AwsSyncClientBuilder; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.Service; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.regions.Regions; import com.amazonaws.services.autoscaling.AmazonAutoScaling; import com.amazonaws.services.autoscaling.AmazonAutoScalingClient; import com.amazonaws.services.autoscaling.AmazonAutoScalingClientBuilder; import com.amazonaws.services.cloudformation.AmazonCloudFormation; import com.amazonaws.services.cloudformation.AmazonCloudFormationClient; import com.amazonaws.services.cloudformation.AmazonCloudFormationClientBuilder; import com.amazonaws.services.cloudfront.AmazonCloudFront; import com.amazonaws.services.cloudfront.AmazonCloudFrontClient; import com.amazonaws.services.cloudfront.AmazonCloudFrontClientBuilder; import com.amazonaws.services.codecommit.AWSCodeCommit; import com.amazonaws.services.codecommit.AWSCodeCommitClient; import com.amazonaws.services.codecommit.AWSCodeCommitClientBuilder; import com.amazonaws.services.codedeploy.AmazonCodeDeploy; import com.amazonaws.services.codedeploy.AmazonCodeDeployClient; import com.amazonaws.services.codedeploy.AmazonCodeDeployClientBuilder; import com.amazonaws.services.codestar.AWSCodeStar; import com.amazonaws.services.codestar.AWSCodeStarClientBuilder; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalkClient; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalkClientBuilder; import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancing; import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClient; import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClientBuilder; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import com.amazonaws.services.lambda.AWSLambda; import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.AWSLambdaClientBuilder; import com.amazonaws.services.logs.AWSLogs; import com.amazonaws.services.logs.AWSLogsClientBuilder; import com.amazonaws.services.opsworks.AWSOpsWorks; import com.amazonaws.services.opsworks.AWSOpsWorksClient; import com.amazonaws.services.opsworks.AWSOpsWorksClientBuilder; import com.amazonaws.services.rds.AmazonRDS; import com.amazonaws.services.rds.AmazonRDSClient; import com.amazonaws.services.rds.AmazonRDSClientBuilder; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; import com.amazonaws.services.simpledb.AmazonSimpleDB; import com.amazonaws.services.simpledb.AmazonSimpleDBClient; import com.amazonaws.services.simpledb.AmazonSimpleDBClientBuilder; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.AmazonSNSClient; import com.amazonaws.services.sns.AmazonSNSClientBuilder; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; /** * Factory for creating AWS clients. */ public class AWSClientFactory { /** * This constant is intended only for testing so that unit tests can * override the Eclipse preference store implementation of AccountInfo. */ public static final String ACCOUNT_INFO_OVERRIDE_PROPERTY = "com.amazonaws.eclipse.test.AccountInfoOverride"; /** Manages the cached client objects by endpoint. */ private CachedClients cachedClientsByEndpoint = new CachedClients(); /** Manages the cached client objects by region. **/ private CachedClients cachedClients = new CachedClients(); private final String accountId; /** * The account info for accessing the user's credentials. */ private AccountInfo accountInfo; private AWSCredentialsProvider credentialsProviderOverride; /** * Constructs a client factory that uses the given account identifier to * retrieve its credentials. */ public AWSClientFactory(String accountId) { AwsToolkitCore plugin = AwsToolkitCore.getDefault(); this.accountId = accountId; accountInfo = plugin.getAccountManager().getAccountInfo(accountId); plugin.getProxyService().addProxyChangeListener(this::onProxyChange); plugin.getAccountManager().addAccountInfoChangeListener(this::onAccountInfoChange); } /** * Decoupling AWS Client Factory from AwsToolkitCore for testing purpose only. * @TestOnly */ public AWSClientFactory(AWSCredentialsProvider credentialsProvider) { this.accountId = null; this.credentialsProviderOverride = credentialsProvider; } private void onProxyChange(IProxyChangeEvent e) { onAccountInfoChange(); } private void onAccountInfoChange() { // When the system AWS accounts refresh, we need to refresh the member variable accountInfo as well in case it is still referencing the previous credentials. accountInfo = AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(accountId); cachedClientsByEndpoint.invalidateClients(); cachedClients.invalidateClients(); } // Returns an anonymous S3 client in us-east-1 region for fetching public-read files. public static AmazonS3 getAnonymousS3Client() { final String serviceEndpoint = RegionUtils.S3_US_EAST_1_REGIONAL_ENDPOINT; final String serviceRegion = Regions.US_EAST_1.getName(); ClientConfiguration clientConfiguration = createClientConfiguration(serviceEndpoint); return AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(new AnonymousAWSCredentials())) .withEndpointConfiguration(new EndpointConfiguration(serviceEndpoint, serviceRegion)) .withClientConfiguration(clientConfiguration) .build(); } /** * Returns a client for the region where the given bucket resides. No * caching is performed on the region lookup. */ public AmazonS3 getS3ClientForBucket(String bucketName) { return getS3ClientByRegion(getS3BucketRegion(bucketName)); } /** * Returns the endpoint appropriate to the given bucket. */ public String getS3BucketEndpoint(String bucketName) { return RegionUtils.getRegion(getS3BucketRegion(bucketName)) .getServiceEndpoint(ServiceAbbreviations.S3); } /** * Returns the standard region the bucket is located. */ private String getS3BucketRegion(String bucketName) { AmazonS3 s3Client = getS3Client(); String region = s3Client.getBucketLocation(bucketName); if (region == null || region.equals("US") ) { region = Regions.US_EAST_1.getName(); } return region; } /* * Simple getters return a client configured with the currently selected region. */ public AmazonS3 getS3Client() { return getS3ClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonCloudFront getCloudFrontClient() { return getCloudFrontClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonSimpleDB getSimpleDBClient() { return getSimpleDBClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonRDS getRDSClient() { return getRDSClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonSQS getSQSClient() { return getSQSClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonSNS getSNSClient() { return getSNSClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonDynamoDB getDynamoDBV2Client() { return getDynamoDBClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AWSSecurityTokenService getSecurityTokenServiceClient() { return getSecurityTokenServiceByRegion(RegionUtils.getCurrentRegion().getId()); } public AWSElasticBeanstalk getElasticBeanstalkClient() { return getElasticBeanstalkClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonIdentityManagement getIAMClient() { return getIAMClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonCloudFormation getCloudFormationClient() { return getCloudFormationClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonEC2 getEC2Client() { return getEC2ClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AmazonCodeDeploy getCodeDeployClient() { return getCodeDeployClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AWSOpsWorks getOpsWorksClient() { return getOpsWorksClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AWSLambda getLambdaClient() { return getLambdaClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AWSCodeCommit getCodeCommitClient() { return getCodeCommitClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AWSCodeStar getCodeStarClient() { return getCodeStarClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AWSLogs getLogsClient() { return getLogsClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AWSKMS getKmsClient() { return getKmsClientByRegion(RegionUtils.getCurrentRegion().getId()); } public AWSSecurityTokenService getSTSClient() { return getSecurityTokenServiceByRegion(RegionUtils.getCurrentRegion().getId()); } /* * Endpoint-specific getters return clients that use the endpoint given. */ @Deprecated public AmazonIdentityManagement getIAMClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AmazonIdentityManagementClient.class); } @Deprecated public AmazonCloudFront getCloudFrontClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AmazonCloudFrontClient.class); } @Deprecated public AmazonEC2 getEC2ClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AmazonEC2Client.class); } @Deprecated public AmazonSimpleDB getSimpleDBClientByEndpoint(final String endpoint) { return getOrCreateClient(endpoint, AmazonSimpleDBClient.class); } @Deprecated public AmazonRDS getRDSClientByEndpoint(final String endpoint) { return getOrCreateClient(endpoint, AmazonRDSClient.class); } @Deprecated public AmazonSQS getSQSClientByEndpoint(final String endpoint) { return getOrCreateClient(endpoint, AmazonSQSClient.class); } @Deprecated public AmazonSNS getSNSClientByEndpoint(final String endpoint) { return getOrCreateClient(endpoint, AmazonSNSClient.class); } @Deprecated public AWSElasticBeanstalk getElasticBeanstalkClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AWSElasticBeanstalkClient.class); } @Deprecated public AmazonElasticLoadBalancing getElasticLoadBalancingClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AmazonElasticLoadBalancingClient.class); } @Deprecated public AmazonAutoScaling getAutoScalingClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AmazonAutoScalingClient.class); } @Deprecated public AmazonDynamoDB getDynamoDBClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AmazonDynamoDBClient.class); } @Deprecated public com.amazonaws.services.dynamodbv2.AmazonDynamoDB getDynamoDBV2ClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.class); } @Deprecated public AmazonCloudFormation getCloudFormationClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AmazonCloudFormationClient.class); } @Deprecated public AmazonCodeDeploy getCodeDeployClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AmazonCodeDeployClient.class); } @Deprecated public AWSOpsWorks getOpsWorksClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AWSOpsWorksClient.class); } @Deprecated public AWSLambda getLambdaClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AWSLambdaClient.class); } @Deprecated public AWSCodeCommit getCodeCommitClientByEndpoint(String endpoint) { return getOrCreateClient(endpoint, AWSCodeCommitClient.class); } /** * Return an AWS client of the specified region by using the ClientBuilder. * * @param regionId - region id for the client, ex. us-esat-1 * @return The cached client if already created, otherwise, create a new one. * Return null if the specified regionId is invalid. */ public AmazonIdentityManagement getIAMClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.IAM, regionId, AmazonIdentityManagementClientBuilder.standard(), AmazonIdentityManagement.class, true); } public AmazonCloudFront getCloudFrontClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.CLOUDFRONT, regionId, AmazonCloudFrontClientBuilder.standard(), AmazonCloudFront.class, true); } /** * Return regional S3 client other than the global one which is built by the default S3 client builder. */ public AmazonS3 getS3ClientByRegion(String regionId) { if (Regions.US_EAST_1.getName().equals(regionId)) { synchronized (AmazonS3.class) { if ( cachedClients.getClient(regionId, AmazonS3.class) == null ) { cachedClients.cacheClient(regionId, AmazonS3.class, createS3UsEast1RegionalClient()); } } return cachedClients.getClient(regionId, AmazonS3.class); } else { return getOrCreateClientByRegion(ServiceAbbreviations.S3, regionId, AmazonS3ClientBuilder.standard(), AmazonS3.class); } } public AmazonEC2 getEC2ClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.EC2, regionId, AmazonEC2ClientBuilder.standard(), AmazonEC2.class); } public AmazonSimpleDB getSimpleDBClientByRegion(final String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.SIMPLEDB, regionId, AmazonSimpleDBClientBuilder.standard(), AmazonSimpleDB.class); } public AmazonRDS getRDSClientByRegion(final String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.RDS, regionId, AmazonRDSClientBuilder.standard(), AmazonRDS.class); } public AmazonSQS getSQSClientByRegion(final String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.SQS, regionId, AmazonSQSClientBuilder.standard(), AmazonSQS.class); } public AmazonSNS getSNSClientByRegion(final String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.SNS, regionId, AmazonSNSClientBuilder.standard(), AmazonSNS.class); } public AWSElasticBeanstalk getElasticBeanstalkClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.BEANSTALK, regionId, AWSElasticBeanstalkClientBuilder.standard(), AWSElasticBeanstalk.class); } public AmazonElasticLoadBalancing getElasticLoadBalancingClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.ELB, regionId, AmazonElasticLoadBalancingClientBuilder.standard(), AmazonElasticLoadBalancing.class); } public AmazonAutoScaling getAutoScalingClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.AUTOSCALING, regionId, AmazonAutoScalingClientBuilder.standard(), AmazonAutoScaling.class); } public AmazonDynamoDB getDynamoDBClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.DYNAMODB, regionId, AmazonDynamoDBClientBuilder.standard(), AmazonDynamoDB.class); } public AWSSecurityTokenService getSecurityTokenServiceByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.STS, regionId, AWSSecurityTokenServiceClientBuilder.standard(), AWSSecurityTokenService.class, true); } public AmazonCloudFormation getCloudFormationClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.CLOUD_FORMATION, regionId, AmazonCloudFormationClientBuilder.standard(), AmazonCloudFormation.class); } public AmazonCodeDeploy getCodeDeployClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.CODE_DEPLOY, regionId, AmazonCodeDeployClientBuilder.standard(), AmazonCodeDeploy.class); } public AWSOpsWorks getOpsWorksClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.OPSWORKS, regionId, AWSOpsWorksClientBuilder.standard(), AWSOpsWorks.class); } public AWSLambda getLambdaClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.LAMBDA, regionId, AWSLambdaClientBuilder.standard(), AWSLambda.class); } public AWSCodeCommit getCodeCommitClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.CODECOMMIT, regionId, AWSCodeCommitClientBuilder.standard(), AWSCodeCommit.class); } public AWSCodeStar getCodeStarClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.CODESTAR, regionId, AWSCodeStarClientBuilder.standard(), AWSCodeStar.class); } public AWSLogs getLogsClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.LOGS, regionId, AWSLogsClientBuilder.standard(), AWSLogs.class); } public AWSKMS getKmsClientByRegion(String regionId) { return getOrCreateClientByRegion(ServiceAbbreviations.KMS, regionId, AWSKMSClientBuilder.standard(), AWSKMS.class); } @Deprecated private <T extends AmazonWebServiceClient> T getOrCreateClient(String endpoint, Class<T> clientClass) { synchronized (clientClass) { if ( cachedClientsByEndpoint.getClient(endpoint, clientClass) == null ) { cachedClientsByEndpoint.cacheClient(endpoint, createClient(endpoint, clientClass)); } } return cachedClientsByEndpoint.getClient(endpoint, clientClass); } private <T> T getOrCreateClientByRegion(String serviceName, String regionId, AwsSyncClientBuilder<? extends AwsSyncClientBuilder, T> builder, Class<T> clientClass, boolean isGlobalClient) { Region region = RegionUtils.getRegion(regionId); if (region == null) { return null; } synchronized (clientClass) { if ( cachedClients.getClient(regionId, clientClass) == null ) { cachedClients.cacheClient(regionId, clientClass, createClientByRegion(builder, serviceName, region, isGlobalClient)); } } return cachedClients.getClient(regionId, clientClass); } private <T> T getOrCreateClientByRegion(String serviceName, String regionId, AwsSyncClientBuilder<? extends AwsSyncClientBuilder, T> builder, Class<T> clientClass) { return getOrCreateClientByRegion(serviceName, regionId, builder, clientClass, false); } /** * @deprecated for {@link #createClientByRegion(AwsSyncClientBuilder, String, String)} */ @Deprecated private <T extends AmazonWebServiceClient> T createClient(String endpoint, Class<T> clientClass) { try { Constructor<T> constructor = clientClass.getConstructor(AWSCredentials.class, ClientConfiguration.class); ClientConfiguration config = createClientConfiguration(endpoint); Service service = RegionUtils.getServiceByEndpoint(endpoint); config.setSignerOverride(service.getSignerOverride()); AWSCredentials credentials = null; if (accountInfo.isUseSessionToken()) { credentials = new BasicSessionCredentials( accountInfo.getAccessKey(), accountInfo.getSecretKey(), accountInfo.getSessionToken()); } else { credentials = new BasicAWSCredentials( accountInfo.getAccessKey(), accountInfo.getSecretKey()); } T client = constructor.newInstance(credentials, config); /* * If a serviceId is explicitly specified with the region metadata, * and this client has a 3-argument form of setEndpoint (for sigv4 * overrides), then explicitly pass in the service Id and region Id * in case it can't be parsed from the endpoint URL by the default * setEndpoint method. */ Method sigv4SetEndpointMethod = lookupSigV4SetEndpointMethod(clientClass); if (service.getServiceId() != null && sigv4SetEndpointMethod != null) { Region region = RegionUtils.getRegionByEndpoint(endpoint); sigv4SetEndpointMethod.invoke(client, endpoint, service.getServiceId(), region.getId()); } else { client.setEndpoint(endpoint); } return client; } catch (Exception e) { throw new RuntimeException("Unable to create client: " + e.getMessage(), e); } } // Low layer method for building a service client by using the client builder. private <T> T createClientByRegion(AwsSyncClientBuilder<? extends AwsSyncClientBuilder, T> builder, String serviceName, Region region, boolean isGlobalClient) { String endpoint = region.getServiceEndpoint(serviceName); String signingRegion = isGlobalClient ? region.getGlobalRegionSigningRegion() : region.getId(); if (endpoint != null && signingRegion != null) { builder.withEndpointConfiguration(new EndpointConfiguration(endpoint, signingRegion)); } builder.withCredentials(new AWSStaticCredentialsProvider(getAwsCredentials())).withClientConfiguration(createClientConfiguration(endpoint)); return (T) builder.build(); } /** * Return the regional us-east-1 S3 client. */ private AmazonS3 createS3UsEast1RegionalClient() { return AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(getAwsCredentials())) .withClientConfiguration(createClientConfiguration(RegionUtils.S3_US_EAST_1_REGIONAL_ENDPOINT)) .withEndpointConfiguration(new EndpointConfiguration(RegionUtils.S3_US_EAST_1_REGIONAL_ENDPOINT, Regions.US_EAST_1.getName())) .build(); } /** * Returns the 3-argument form of setEndpoint that is used to override * values for sigv4 signing, or null if the specified class does not support * that version of setEndpoint. * * @param clientClass * The class to introspect. * * @return The 3-argument method form of setEndpoint, or null if it doesn't * exist in the specified class. */ private <T extends AmazonWebServiceClient> Method lookupSigV4SetEndpointMethod(Class<T> clientClass) { try { return clientClass.getMethod("setEndpoint", String.class, String.class, String.class); } catch (SecurityException e) { throw new RuntimeException("Unable to lookup class methods via reflection", e); } catch (NoSuchMethodException e) { return null; } } private AWSCredentials getAwsCredentials() { AWSCredentials credentials = null; if (credentialsProviderOverride != null) { credentials = credentialsProviderOverride.getCredentials(); } else if (accountInfo.isUseSessionToken()) { credentials = new BasicSessionCredentials( accountInfo.getAccessKey(), accountInfo.getSecretKey(), accountInfo.getSessionToken()); } else { credentials = new BasicAWSCredentials( accountInfo.getAccessKey(), accountInfo.getSecretKey()); } return credentials; } private static ClientConfiguration createClientConfiguration(String secureEndpoint) { ClientConfiguration config = new ClientConfiguration(); IPreferenceStore preferences = AwsToolkitCore.getDefault().getPreferenceStore(); int connectionTimeout = preferences.getInt(PreferenceConstants.P_CONNECTION_TIMEOUT); int socketTimeout = preferences.getInt(PreferenceConstants.P_SOCKET_TIMEOUT); config.setConnectionTimeout(connectionTimeout); config.setSocketTimeout(socketTimeout); config.setUserAgentPrefix(AwsClientUtils.formatUserAgentString("AWS-Toolkit-For-Eclipse", AwsToolkitCore.getDefault())); AwsToolkitCore plugin = AwsToolkitCore.getDefault(); if ( plugin != null ) { IProxyService proxyService = AwsToolkitCore.getDefault().getProxyService(); if ( proxyService.isProxiesEnabled() ) { try { IProxyData[] proxyData; proxyData = proxyService.select(new URI(secureEndpoint)); if ( proxyData.length > 0 ) { config.setProxyHost(proxyData[0].getHost()); config.setProxyPort(proxyData[0].getPort()); if ( proxyData[0].isRequiresAuthentication() ) { config.setProxyUsername(proxyData[0].getUserId()); config.setProxyPassword(proxyData[0].getPassword()); } } } catch ( URISyntaxException e ) { plugin.logError(e.getMessage(), e); } } } return config; } /** * Responsible for managing the various AWS client objects needed for each service/region combination. * This class is thread safe. */ private static class CachedClients { private final Map<Class<?>, Map<String, Object>> cachedClients = new ConcurrentHashMap<>(); @SuppressWarnings("unchecked") public synchronized <T> T getClient(String region, Class<T> clientClass) { if (cachedClients.get(clientClass) == null) { return null; } return (T)cachedClients.get(clientClass).get(region); } public synchronized <T> void cacheClient(String region, T client) { cacheClient(region, null, client); } public <T> void cacheClient(String region, Class<T> clazz, T client) { Class<?> key = clazz == null ? client.getClass() : clazz; if (cachedClients.get(key) == null) { cachedClients.put(key, new ConcurrentHashMap<String, Object>()); } Map<String, Object> map = cachedClients.get(key); map.put(region, client); } public synchronized void invalidateClients() { cachedClients.clear(); } } }
7,551
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/AwsUrls.java
/* * Copyright 2009-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core; /** * Commonly used AWS URL constants. */ public class AwsUrls { public static final String TRACKING_PARAMS = "utm_source=eclipse&utm_medium=ide&utm_campaign=awstoolkitforeclipse"; public static final String SIGN_UP_URL = "http://aws.amazon.com/register" + "?" + TRACKING_PARAMS; public static final String SECURITY_CREDENTIALS_URL = "https://console.aws.amazon.com/iam/home?#security_credential" + "?" + TRACKING_PARAMS; public static final String JAVA_DEVELOPMENT_FORUM_URL = "http://developer.amazonwebservices.com/connect/forum.jspa?forumID=70" + "&" + TRACKING_PARAMS; public static final String AWS_TOOLKIT_FOR_ECLIPSE_HOMEPAGE_URL = "http://aws.amazon.com/eclipse" + "?" + TRACKING_PARAMS; public static final String AWS_TOOLKIT_FOR_ECLIPSE_FAQ_URL = "http://aws.amazon.com/eclipse/faqs/" + "?" + TRACKING_PARAMS; public static final String AWS_TOOLKIT_FOR_ECLIPSE_GITHUB_URL = "https://github.com/amazonwebservices/aws-toolkit-for-eclipse/"; public static final String AWS_MANAGEMENT_CONSOLE_URL = "http://aws.amazon.com/console" + "?" + TRACKING_PARAMS; }
7,552
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/AwsClientUtils.java
/* * Copyright 2009-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core; import java.util.Dictionary; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Plugin; import org.osgi.framework.Bundle; /** * Utilities for working with AWS clients, such as creating consistent user * agent strings for different plugins. */ public final class AwsClientUtils { /** * Forms a user-agent string for clients to send when making service calls, * indicating the name and version of this client. * * @param pluginName * The name of the plugin to use in the user agent string. * @param plugin * The plugin from which to pull version information. * * @return A user-agent string indicating what client and version are * accessing AWS. */ public static String formatUserAgentString( String pluginName, Plugin plugin) { /* * If we aren't running in an OSGi container (ex: during tests), then we * won't have access to pull out the version, but if we are, we can pull * it out of the bundle-version property. */ String version = "???"; if ( plugin != null ) { Dictionary headers = plugin.getBundle().getHeaders(); version = (String) headers.get("Bundle-Version"); } String userAgentValue = pluginName + "/" + version; Bundle runtimeCore = Platform.getBundle("org.eclipse.core.runtime"); if ( runtimeCore != null ) { Dictionary headers = runtimeCore.getHeaders(); version = (String) headers.get("Bundle-Version"); userAgentValue += ", Eclipse/" + version; } return userAgentValue; } @Deprecated public String formUserAgentString(String pluginName, Plugin plugin) { return formatUserAgentString(pluginName, plugin); } @Deprecated public AwsClientUtils() { } }
7,553
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/AccountInfo.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core; /** * Interface for accessing and saving configured AWS account information. */ public interface AccountInfo { /** * @return The account identifier used internally by the plugin. */ public String getInternalAccountId(); /** * @return The UI-friendly name for this account. */ public String getAccountName(); /** * Sets the UI-friendly name for this account. * * @param accountName * The UI-friendly name for this account. */ public void setAccountName(String accountName); /** * @return The currently configured AWS user access key. */ public String getAccessKey(); /** * Sets the AWS Access Key ID for this account info object. * * @param accessKey The AWS Access Key ID. */ public void setAccessKey(String accessKey); /** * @return The currently configured AWS secret key. */ public String getSecretKey(); /** * Sets the AWS Secret Access Key for this account info object. * * @param secretKey The AWS Secret Access Key. */ public void setSecretKey(String secretKey); /** * @return true if the current account includes a session token */ public boolean isUseSessionToken(); /** * Sets whether the current account includes a session token * * @param useSessionToken * true if the current account includes a session token */ public void setUseSessionToken(boolean useSessionToken); /** * @return The currently configured AWS session token. */ public String getSessionToken(); /** * Sets the AWS session token for this account info object. * * @param sessionToken The AWS session token. */ public void setSessionToken(String sessionToken); /** * Returns the currently configured AWS user account ID. * * @return The currently configured AWS user account ID. */ public String getUserId(); /** * Sets the currently configured AWS user account ID. */ public void setUserId(String userId); /** * Returns the currently configured EC2 private key file. * * @return The currently configured EC2 private key file. */ public String getEc2PrivateKeyFile(); /** * Sets the currently configured EC2 private key file. */ public void setEc2PrivateKeyFile(String ec2PrivateKeyFile); /** * Returns the currently configured EC2 certificate file. * * @return The currently configured EC2 certificate file. */ public String getEc2CertificateFile(); /** * Sets the currently configured EC2 certificate file. */ public void setEc2CertificateFile(String ec2CertificateFile); /** * Persist this account information in the source where it was loaded, e.g. * save the related preference store properties, or save output the * information to an external file. */ public void save(); /** * Delete this account information in the source where it was loaded. */ public void delete(); /** * Returns true if this account information contains in-memory changes that * are not saved in the source yet. */ public boolean isDirty(); /** * Returns true if the configured account information appears to be valid by * verifying that none of the values are missing. * * @return True if the configured account information appears to be valid, * otherwise false. */ public boolean isValid(); /** * Returns true if and only if the configured certificate and corresponding * private key are valid. Currently that distinction is made by verifying * that the referenced files exist. * * @return True if and only if the configured certificate and corresponding * private key are valid. */ public boolean isCertificateValid(); }
7,554
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/BrowserUtils.java
/* * Copyright 2010-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core; import java.net.URL; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; public class BrowserUtils { private static final int BROWSER_STYLE = IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.AS_EXTERNAL | IWorkbenchBrowserSupport.STATUS | IWorkbenchBrowserSupport.NAVIGATION_BAR; /** * Opens the specified URL in an external browser window. * @param url The URL to open. * @throws PartInitException */ public static void openExternalBrowser(URL url) throws PartInitException { IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport(); browserSupport.createBrowser(BROWSER_STYLE, null, null, null) .openURL(url); } public static void openExternalBrowser(String url) { try { openExternalBrowser(new URL(url)); } catch (Exception e) { AwsToolkitCore.getDefault().reportException( "Unable to open external web browser to '" + url + "': " + e.getMessage(), e); } } }
7,555
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/SelectOrCreateKmsKeyComposite.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase; import com.amazonaws.eclipse.core.model.SelectOrCreateKmsKeyDataModel; import com.amazonaws.eclipse.core.model.SelectOrCreateKmsKeyDataModel.KmsKey; import com.amazonaws.eclipse.core.ui.dialogs.AbstractInputDialog; import com.amazonaws.eclipse.core.ui.dialogs.CreateKmsKeyDialog; public class SelectOrCreateKmsKeyComposite extends SelectOrCreateComposite<KmsKey, SelectOrCreateKmsKeyDataModel, AwsResourceScopeParamBase> { public SelectOrCreateKmsKeyComposite( Composite parent, DataBindingContext bindingContext, SelectOrCreateKmsKeyDataModel dataModel) { super(parent, bindingContext, dataModel, "KMS Key:"); } @Override protected AbstractInputDialog<KmsKey> createResourceDialog(AwsResourceScopeParamBase param) { return new CreateKmsKeyDialog(Display.getCurrent().getActiveShell(), param); } }
7,556
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/MultipleSelectionListComposite.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newControlDecoration; import java.util.Arrays; import java.util.List; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.validation.MultiValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.fieldassist.ControlDecoration; 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.Table; import org.eclipse.swt.widgets.TableItem; import com.amazonaws.eclipse.core.model.MultipleSelectionListDataModel; import com.amazonaws.eclipse.databinding.DecorationChangeListener; /** * A reusable Composite for multiple selection using check box. */ public class MultipleSelectionListComposite<T> extends Composite { private final MultipleSelectionListDataModel<T> dataModel; private final ListSelectionNotEmptyValidator<T> validator; private Table table; public MultipleSelectionListComposite( Composite parent, DataBindingContext context, MultipleSelectionListDataModel<T> dataModel, List<T> itemSet, List<T> defaultSelected, String selectedItemsEmptyErrorMessage) { super(parent, SWT.NONE); setLayout(new GridLayout(1, false)); setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.dataModel = dataModel; this.validator = new ListSelectionNotEmptyValidator<>( dataModel.getSelectedList(), selectedItemsEmptyErrorMessage); createControl(context, itemSet, defaultSelected); } private void createControl(DataBindingContext context, List<T> itemSet, List<T> defaultSelected) { table = new Table(this, SWT.CHECK | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY); table.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); for (T item : itemSet) { TableItem tableItem = new TableItem(table, SWT.NONE); tableItem.setData(item); tableItem.setText(item.toString()); if (defaultSelected != null && defaultSelected.contains(item)) { tableItem.setChecked(true); } } ControlDecoration controlDecoration = newControlDecoration(table, ""); context.addValidationStatusProvider(validator); new DecorationChangeListener(controlDecoration, validator.getValidationStatus()); table.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onTableItemSelected(); } }); onTableItemSelected(); } private void onTableItemSelected() { List<T> selectedItems = dataModel.getSelectedList(); selectedItems.clear(); Arrays.stream(table.getItems()) .filter(TableItem::getChecked) .forEach(tt -> selectedItems.add((T)tt.getData())); validator.revalidateDelegate(); } private static class ListSelectionNotEmptyValidator<T> extends MultiValidator { private final List<T> model; private final String errorMessage; public ListSelectionNotEmptyValidator(List<T> selectedItems, String emptyErrorMessage) { this.model = selectedItems; this.errorMessage = emptyErrorMessage; } @Override protected IStatus validate() { if (model == null || model.isEmpty()) { return ValidationStatus.error(errorMessage); } return ValidationStatus.ok(); } // We need to expose the protected revalidate method to explicitly refresh the validation status. public void revalidateDelegate() { revalidate(); } } }
7,557
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/RegionComposite.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import static com.amazonaws.util.ValidationUtils.assertNotNull; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; 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.model.RegionDataModel; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.widget.ComboViewerComplex; /** * A reusable composite for Region selection. */ public class RegionComposite extends Composite { private static final Region DEFAULT_REGION = RegionUtils.getRegion("us-east-1"); private final DataBindingContext bindingContext; private final RegionDataModel dataModel; private final String serviceName; private final String labelValue; private final List<ISelectionChangedListener> listeners; private ComboViewerComplex<Region> regionComboComplex; private RegionComposite( Composite parent, DataBindingContext bindingContext, RegionDataModel dataModel, String serviceName, String labelValue, List<ISelectionChangedListener> listeners) { super(parent, SWT.NONE); this.bindingContext = bindingContext; this.dataModel = dataModel; this.serviceName = serviceName; this.labelValue = labelValue; this.listeners = listeners; this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); this.setLayout(new GridLayout(3, false)); createControl(); } public Region getCurrentSelectedRegion() { IStructuredSelection selection = (IStructuredSelection) regionComboComplex.getComboViewer().getSelection(); return (Region) selection.getFirstElement(); } private void createControl() { List<Region> regions = serviceName == null ? RegionUtils.getRegions() : RegionUtils.getRegionsForService(serviceName); regionComboComplex = ComboViewerComplex.<Region>builder() .composite(this) .bindingContext(bindingContext) .labelValue(labelValue) .items(regions) .defaultItem(Optional.ofNullable(dataModel.getRegion()).orElse(DEFAULT_REGION)) .addListeners(listeners) .pojoObservableValue(PojoProperties.value(RegionDataModel.class, RegionDataModel.P_REGION, Region.class).observe(dataModel)) .labelProvider(new LabelProvider() { @Override public String getText(Object element) { if (element instanceof Region) { Region region = (Region) element; return region.getName(); } return super.getText(element); } }) .comboSpan(2) .build(); } public void selectAwsRegion(Region region) { regionComboComplex.getComboViewer().setSelection(new StructuredSelection(Optional.ofNullable(region).orElse(DEFAULT_REGION))); } public static RegionCompositeBuilder builder() { return new RegionCompositeBuilder(); } public static final class RegionCompositeBuilder { private Composite parent; private DataBindingContext bindingContext; private RegionDataModel dataModel; private String serviceName; private String labelValue = "Select region:"; private final List<ISelectionChangedListener> listeners = new ArrayList<>(); public RegionComposite build() { validateParameters(); return new RegionComposite(parent, bindingContext, dataModel, serviceName, labelValue, listeners); } public RegionCompositeBuilder parent(Composite parent) { this.parent = parent; return this; } public RegionCompositeBuilder bindingContext(DataBindingContext bindingContext) { this.bindingContext = bindingContext; return this; } public RegionCompositeBuilder dataModel(RegionDataModel dataModel) { this.dataModel = dataModel; return this; } public RegionCompositeBuilder serviceName(String serviceName) { this.serviceName = serviceName; return this; } public RegionCompositeBuilder labelValue(String labelValue) { this.labelValue = labelValue; return this; } public RegionCompositeBuilder addListener(ISelectionChangedListener listener) { this.listeners.add(listener); return this; } private void validateParameters() { assertNotNull(parent, "Parent composite"); assertNotNull(bindingContext, "BindingContext"); assertNotNull(dataModel, "RegionDataModel"); } } }
7,558
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/KeyValueSetEditingComposite.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; 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.validation.IValidator; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.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.Shell; import org.eclipse.swt.widgets.TableColumn; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.model.KeyValueSetDataModel; import com.amazonaws.eclipse.core.model.KeyValueSetDataModel.Pair; import com.amazonaws.eclipse.core.validator.KeyNotDuplicateValidator; import com.amazonaws.eclipse.core.widget.TextComplex; import com.amazonaws.eclipse.databinding.NotEmptyValidator; public class KeyValueSetEditingComposite extends Composite { private final KeyValueSetDataModel dataModel; private TableViewer viewer; private Button addButton; private Button editButton; private Button removeButton; private Button saveButton; private final KeyValueEditingUiText uiText; private String addButtonText = "Add"; private String editButtonText = "Edit"; private String removeButtonText = "Remove"; private String saveButtonText = "Save"; private String keyColLabel = "name"; private String valueColLabel = "value"; private final List<IValidator> keyValidators; private final List<IValidator> valueValidators; private final SelectionListener saveListener; private KeyValueSetEditingComposite(Composite parent, KeyValueSetDataModel dataModel, List<IValidator> keyValidators, List<IValidator> valueValidators, SelectionListener saveListener, KeyValueEditingUiText uiText) { super(parent, SWT.BORDER); this.dataModel = dataModel; this.keyValidators = keyValidators; this.valueValidators = valueValidators; this.saveListener = saveListener; this.uiText = uiText; setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); setLayout(new GridLayout()); createControl(); initButtonsStatus(); } private void createControl() { createTagsTableViewerSection(); createButtonsSection(); } private void createTagsTableViewerSection() { Composite container = new Composite(this, SWT.NONE); TableColumnLayout tableColumnLayout = new TableColumnLayout(); container.setLayout(tableColumnLayout); container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); viewer = new TableViewer(container, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); viewer.getControl().setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true)); viewer.getTable().setHeaderVisible(true); viewer.getTable().setLinesVisible(true); viewer.setContentProvider(new ArrayContentProvider()); createColumns(viewer, tableColumnLayout); viewer.setInput(dataModel.getPairSet()); viewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent e) { onEditButton(); } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent arg0) { onSelectionChanged(); } }); } private void createButtonsSection() { Composite buttonPanel = new Composite(this, SWT.NONE); buttonPanel.setLayout(new GridLayout(4, false)); buttonPanel.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); addButton = new Button(buttonPanel, SWT.PUSH); addButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD)); addButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Pair newPair = new Pair("", ""); if (Window.OK == new KeyValueEditingDialog(getShell(), dataModel.getPairSet(), newPair, uiText.getAddDialogTitle(), uiText.getAddDialogMessage(), uiText.getKeyLabelText(), uiText.getValueLabelText()).open()) { dataModel.getPairSet().add(newPair); refreshOnEditing(); } } }); addButton.setText(addButtonText()); editButton = new Button(buttonPanel, SWT.PUSH); editButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_EDIT)); editButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onEditButton(); } }); editButton.setText(editButtonText); removeButton = new Button(buttonPanel, SWT.PUSH); removeButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_REMOVE)); removeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (Pair pair : getSelectedObjects()) { dataModel.getPairSet().remove(pair); } refreshOnEditing(); } }); removeButton.setText(removeButtonText); saveButton = new Button(buttonPanel, SWT.PUSH); saveButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_SAVE)); if (saveListener != null) { saveButton.addSelectionListener(saveListener); } saveButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { saveButton.setEnabled(false); } }); saveButton.setText(saveButtonText); } private void onEditButton() { Collection<Pair> selectedPairs = getSelectedObjects(); for (Pair pair : selectedPairs) { String oldKey = pair.getKey(); String oldValue = pair.getValue(); if (Window.OK != new KeyValueEditingDialog(getShell(), dataModel.getPairSet(), pair, uiText.getEditDialogTitle(), uiText.getEditDialogMessage(), uiText.getKeyLabelText(), uiText.getValueLabelText()).open()) { pair.setKey(oldKey); pair.setValue(oldValue); } refreshOnEditing(); } } public void refresh() { updateUI(true); } private void updateUI(boolean initialRefresh) { viewer.refresh(); addButton.setText(addButtonText()); addButton.setEnabled(dataModel.isUnlimitedPairs() || dataModel.getPairSet().size() < dataModel.getMaxPairs()); saveButton.setEnabled(!initialRefresh); } private void refreshOnEditing() { updateUI(false); } private String addButtonText() { return dataModel.isUnlimitedPairs() ? addButtonText : String.format("%s (%d left)", addButtonText, dataModel.getMaxPairs() - dataModel.getPairSet().size()); } private void initButtonsStatus() { editButton.setEnabled(false); removeButton.setEnabled(false); saveButton.setEnabled(false); } private void onSelectionChanged() { boolean objectSelected = getSelectedObjects().size() > 0; editButton.setEnabled(objectSelected); removeButton.setEnabled(objectSelected); } private void createColumns(TableViewer viewer, TableColumnLayout layout) { createColumn(viewer, 0, keyColLabel, layout); createColumn(viewer, 1, valueColLabel, layout); } private Collection<Pair> getSelectedObjects() { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); List<Pair> pairs = new LinkedList<>(); Iterator<?> iter = s.iterator(); while (iter.hasNext()) { Object next = iter.next(); if (next instanceof Pair) pairs.add((Pair)next); } return pairs; } private TableViewerColumn createColumn(final TableViewer viewer, final int index, final String text, final TableColumnLayout layout) { TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE); TableColumn column = viewerColumn.getColumn(); column.setText(text); viewerColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Pair pair = (Pair) element; switch (index) { case 0: return pair.getKey(); case 1: return pair.getValue(); } return element.toString(); } }); layout.setColumnData(column, new ColumnWeightData(50, 200, true)); return viewerColumn; } public static class KeyValueEditingUiText { private String addDialogTitle = "Add Tag"; private String addDialogMessage = "Add a new tag"; private String editDialogTitle = "Edit Tag"; private String editDialogMessage = "Edit the existing tag"; private String keyLabelText = "Tag Name:"; private String valueLabelText = "Tag Value:"; public KeyValueEditingUiText() {} public KeyValueEditingUiText(String addDialogTitle, String addDialogMessage, String editDialogTitle, String editDialogMessage, String keyLabelText, String valueLabelText) { this.addDialogTitle = addDialogTitle; this.addDialogMessage = addDialogMessage; this.editDialogTitle = editDialogTitle; this.editDialogMessage = editDialogMessage; this.keyLabelText = keyLabelText; this.valueLabelText = valueLabelText; } public String getAddDialogTitle() { return addDialogTitle; } public void setAddDialogTitle(String addDialogTitle) { this.addDialogTitle = addDialogTitle; } public String getAddDialogMessage() { return addDialogMessage; } public void setAddDialogMessage(String addDialogMessage) { this.addDialogMessage = addDialogMessage; } public String getEditDialogTitle() { return editDialogTitle; } public void setEditDialogTitle(String editDialogTitle) { this.editDialogTitle = editDialogTitle; } public String getEditDialogMessage() { return editDialogMessage; } public void setEditDialogMessage(String editDialogMessage) { this.editDialogMessage = editDialogMessage; } public String getKeyLabelText() { return keyLabelText; } public void setKeyLabelText(String keyLabelText) { this.keyLabelText = keyLabelText; } public String getValueLabelText() { return valueLabelText; } public void setValueLabelText(String valueLabelText) { this.valueLabelText = valueLabelText; } } public static class KeyValueSetEditingCompositeBuilder { private List<IValidator> keyValidators = new ArrayList<>(); private List<IValidator> valueValidators = new ArrayList<>(); private SelectionListener saveListener; private KeyValueEditingUiText uiText = new KeyValueEditingUiText(); public KeyValueSetEditingComposite build(Composite parent, KeyValueSetDataModel dataModel) { return new KeyValueSetEditingComposite(parent, dataModel, keyValidators, valueValidators, saveListener, uiText); } public KeyValueSetEditingCompositeBuilder addKeyValidator(IValidator validator) { this.keyValidators.add(validator); return this; } public KeyValueSetEditingCompositeBuilder addValueValidator(IValidator validator) { this.valueValidators.add(validator); return this; } public KeyValueSetEditingCompositeBuilder saveListener(SelectionListener saveListener) { this.saveListener = saveListener; return this; } public KeyValueSetEditingCompositeBuilder uiText(KeyValueEditingUiText uiText) { this.uiText = uiText; return this; } } private class KeyValueEditingDialog extends TitleAreaDialog { private final DataBindingContext dataBindingContext = new DataBindingContext(); private final AggregateValidationStatus aggregateValidationStatus; private final List<Pair> pairSet; private final Pair pairModel; private TextComplex keyText; private TextComplex valueText; private final String title; private final String message; private final String keyLabel; private final String valueLabel; public KeyValueEditingDialog(Shell parent, List<Pair> pairSet, Pair model, String title, String message, String keyLabel, String valueLabel) { super(parent); this.pairSet = pairSet; this.pairModel = model; this.aggregateValidationStatus = new AggregateValidationStatus( dataBindingContext, AggregateValidationStatus.MAX_SEVERITY); this.title = title; this.message = message; this.keyLabel = keyLabel; this.valueLabel = valueLabel; } @Override public void create() { super.create(); setTitle(title); setMessage(message); aggregateValidationStatus.addChangeListener(new IChangeListener() { @Override public void handleChange(ChangeEvent event) { populateValidationStatus(); } }); populateValidationStatus(); } @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout layout = new GridLayout(2, false); container.setLayout(layout); keyText = TextComplex.builder(container, dataBindingContext, PojoObservables.observeValue(pairModel, Pair.P_KEY)) .labelValue(keyLabel) .defaultValue(pairModel.getKey()) .addValidator(new NotEmptyValidator("The key name cannot be empty.")) .addValidator(new KeyNotDuplicateValidator(pairSet, pairModel, "This field must not contain duplicate items.")) .addValidators(keyValidators) .build(); valueText = TextComplex.builder(container, dataBindingContext, PojoObservables.observeValue(pairModel, Pair.P_VALUE)) .labelValue(valueLabel) .defaultValue(pairModel.getValue()) .addValidators(valueValidators) .build(); return area; } @Override protected boolean isResizable() { return true; } private void populateValidationStatus() { IStatus status = getValidationStatus(); if (status == null) return; if (status.getSeverity() == IStatus.OK) { this.setErrorMessage(null); getButton(IDialogConstants.OK_ID).setEnabled(true); } else { setErrorMessage(status.getMessage()); getButton(IDialogConstants.OK_ID).setEnabled(false); } } private IStatus getValidationStatus() { if (aggregateValidationStatus == null) return null; Object value = aggregateValidationStatus.getValue(); if (!(value instanceof IStatus)) return null; return (IStatus)value; } } }
7,559
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/WebLinkListener.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import java.util.logging.Logger; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import com.amazonaws.eclipse.core.BrowserUtils; import com.amazonaws.eclipse.core.ui.preferences.AwsAccountPreferencePage; /** * Implementation of Listener that opens an internal browser pointing to the * text in the event object and optionally closes a shell after opening the * link if the caller requested that one be closed. */ public class WebLinkListener implements Listener { /** Optional Shell object to close after opening the link */ private Shell shellToClose; /** * Sets the Shell object that should be closed after a link is opened. * This is useful for preference pages so that they can ensure the * preference dialog is closed so that users can see the link that was * just opened. * * @param shell * The Shell to close after opening the selected link. */ public void setShellToClose(Shell shell) { shellToClose = shell; } /* (non-Javadoc) * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event) */ @Override public void handleEvent(Event event) { try { BrowserUtils.openExternalBrowser(event.text); if (shellToClose != null) { shellToClose.close(); } } catch (Exception e) { Logger logger = Logger.getLogger(AwsAccountPreferencePage.class.getName()); logger.warning("Unable to open link to '" + event.text + "': " + e.getMessage()); } } }
7,560
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/AccountSelectionComposite.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Widget; import org.eclipse.ui.dialogs.PreferencesUtil; import com.amazonaws.eclipse.core.AccountInfo; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.ui.preferences.AwsAccountPreferencePage; /** * Reusable composite to select an AWS account, with a link to configure * accounts. */ public class AccountSelectionComposite extends Composite { /** * Combo control for users to select an account */ private Combo accountSelection; private Label noAccounts; private List<SelectionListener> listeners = new LinkedList<>(); /** * Adds a selection listener to the account selection field. */ public void addSelectionListener(SelectionListener listner) { listeners.add(listner); } public AccountSelectionComposite(final Composite parent, final int style) { super(parent, style); setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); setLayout(new GridLayout(3, false)); createChildWidgets(); updateAccounts(); } protected void createChildWidgets() { if ( !validAccountsConfigured() ) { createNoAccountLabel(); } else { createAccountSelectionCombo(); } createAccountConfigurationLink(); } protected void createNoAccountLabel() { noAccounts = new Label(this, SWT.None); noAccounts.setText("No AWS accounts have been configured yet."); GridData gd = new GridData(); gd.horizontalSpan = 2; noAccounts.setLayoutData(gd); } protected void createAccountConfigurationLink() { Link link = new Link(this, SWT.NONE); link.setFont(this.getFont()); link.setText("<A>" + "Configure AWS profiles..." + "</A>"); link.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { PreferencesUtil.createPreferenceDialogOn(Display.getDefault().getActiveShell(), AwsAccountPreferencePage.ID, new String[] { AwsAccountPreferencePage.ID }, null).open(); if ( noAccounts != null && validAccountsConfigured() ) { for ( Widget w : getChildren() ) { w.dispose(); } noAccounts = null; createChildWidgets(); getShell().layout(true, true); } updateAccounts(); } @Override public void widgetDefaultSelected(final SelectionEvent e) { widgetSelected(e); } }); link.setLayoutData(new GridData(SWT.END, SWT.CENTER, false, false)); link.setEnabled(true); } protected void createAccountSelectionCombo() { Label selectAccount = new Label(this, SWT.None); selectAccount.setText("Select profile:"); this.accountSelection = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY); accountSelection.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for ( SelectionListener listener : listeners ) { listener.widgetSelected(e); } } }); } /** * Returns whether there are valid aws accounts configured */ private boolean validAccountsConfigured() { return AwsToolkitCore.getDefault().getAccountManager().validAccountsConfigured(); } /** * Updates the list of accounts from the global store, preserving selection * when possible. Called automatically upon composite construction and after * the preference page link is clicked. */ public void updateAccounts() { if ( accountSelection == null ) return; String currentAccount = this.accountSelection.getText(); Map<String, String> accounts = AwsToolkitCore.getDefault().getAccountManager().getAllAccountNames(); List<String> accountNames = new ArrayList<>(); accountNames.addAll(accounts.values()); Collections.sort(accountNames); this.accountSelection.setItems(accountNames.toArray(new String[accountNames.size()])); for ( Entry<String, String> entry : accounts.entrySet() ) { this.accountSelection.setData(entry.getValue(), entry.getKey()); } int selectedIndex = 0; if ( currentAccount != null ) { for ( int i = 0; i < this.accountSelection.getItemCount(); i++ ) { if ( currentAccount.equals(this.accountSelection.getItem(i)) ) { selectedIndex = i; break; } } if ( this.accountSelection.getItemCount() > 0 ) { this.accountSelection.select(selectedIndex); } } else { selectAccountId(AwsToolkitCore.getDefault().getCurrentAccountId()); } getParent().layout(true, true); } /** * Selects the given account name (not id) in the list */ public void selectAccountName(final String accountName) { if ( accountSelection == null ) return; int selectedIndex = -1; if ( accountName != null ) { for ( int i = 0; i < this.accountSelection.getItemCount(); i++ ) { if ( accountName.equals(this.accountSelection.getItem(i)) ) { selectedIndex = i; break; } } } if ( selectedIndex >= 0 && this.accountSelection.getItemCount() > 0 ) { this.accountSelection.select(selectedIndex); } } /** * Selects the given account id (not name) in the list */ public void selectAccountId(final String accountId) { if ( accountSelection == null ) return; int selectedIndex = -1; if ( accountId != null ) { for ( int i = 0; i < this.accountSelection.getItemCount(); i++ ) { if ( this.accountSelection.getData(this.accountSelection.getItem(i)).equals(accountId) ) { selectedIndex = i; break; } } } if ( selectedIndex >= 0 && this.accountSelection.getItemCount() > 0 ) { this.accountSelection.select(selectedIndex); } } /** * Returns the id (not name) of the selected account. In the case that the * customer hasn't configured any accounts yet, this returns the default * account id. */ public String getSelectedAccountId() { if ( !validAccountsConfigured() ) return AwsToolkitCore.getDefault().getCurrentAccountId(); return (String) this.accountSelection.getData(this.accountSelection.getText()); } /** * Returns whether a correctly configured account is selected. */ public boolean isValidAccountSelected() { AccountInfo info = AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(getSelectedAccountId()); return (info != null && info.isValid()); } }
7,561
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/MavenConfigurationComposite.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import static com.amazonaws.eclipse.core.model.MavenConfigurationDataModel.P_ARTIFACT_ID; import static com.amazonaws.eclipse.core.model.MavenConfigurationDataModel.P_GROUP_ID; import static com.amazonaws.eclipse.core.model.MavenConfigurationDataModel.P_PACKAGE_NAME; import static com.amazonaws.eclipse.core.model.MavenConfigurationDataModel.P_VERSION; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; 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.maven.MavenFactory; import com.amazonaws.eclipse.core.model.MavenConfigurationDataModel; import com.amazonaws.eclipse.core.validator.PackageNameValidator; import com.amazonaws.eclipse.core.widget.TextComplex; import com.amazonaws.eclipse.databinding.NotEmptyValidator; /** * A reusable Maven configuration composite including configurations such as group id, artifact id etc. */ public class MavenConfigurationComposite extends Composite { private TextComplex groupIdComplex; private TextComplex artifactIdComplex; private TextComplex versionComplex; private TextComplex packageComplex; public MavenConfigurationComposite(Composite parent, DataBindingContext context, MavenConfigurationDataModel dataModel) { super(parent, SWT.NONE); setLayout(new GridLayout(2, false)); setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); createControl(context, dataModel); } private void createControl(DataBindingContext context, MavenConfigurationDataModel dataModel) { groupIdComplex = TextComplex.builder(this, context, PojoObservables.observeValue(dataModel, P_GROUP_ID)) .addValidator(new NotEmptyValidator("Group ID must be provided!")) .modifyListener(e -> { onMavenConfigurationChange(); }) .labelValue("Group ID:") .defaultValue(dataModel.getGroupId()) .build(); artifactIdComplex = TextComplex.builder(this, context, PojoObservables.observeValue(dataModel, P_ARTIFACT_ID)) .addValidator(new NotEmptyValidator("Artifact ID must be provided!")) .modifyListener(e -> { onMavenConfigurationChange(); }) .labelValue("Artifact ID:") .defaultValue(dataModel.getArtifactId()) .build(); versionComplex = TextComplex.builder(this, context, PojoObservables.observeValue(dataModel, P_VERSION)) .addValidator(new NotEmptyValidator("Version must be provided!")) .labelValue("Version:") .defaultValue(dataModel.getVersion()) .build(); packageComplex = TextComplex.builder(this, context, PojoObservables.observeValue(dataModel, P_PACKAGE_NAME)) .addValidator(new PackageNameValidator("Package name must be provided!")) .labelValue("Package name:") .defaultValue(dataModel.getPackageName()) .build(); } private void onMavenConfigurationChange() { if (packageComplex != null && groupIdComplex != null && artifactIdComplex != null) { String groupId = groupIdComplex.getText().getText(); String artifactId = artifactIdComplex.getText().getText(); packageComplex.setText(MavenFactory.assumePackageName(groupId, artifactId)); } } }
7,562
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/DeleteResourceConfirmationDialog.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.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; /** * A reusable dialog for confirming deleting an AWS resource. */ public class DeleteResourceConfirmationDialog extends TitleAreaDialog { private final String resourceName; private final String title; private final String message; private final String deleteResourceLabel; private final String deleteConfirmationLabel; private Text resourceNameText; public DeleteResourceConfirmationDialog(Shell parentShell, String resourceName, String resource) { super(parentShell); this.resourceName = resourceName; this.title = String.format("Delete %s", resource); this.message = String.format("Delete the %s %s permanently? This cannot be undone.", resource, resourceName); this.deleteResourceLabel = String.format("Type the name of the %s to confirm deletion:", resource); this.deleteConfirmationLabel = String.format("Are you sure you want to delete this %s permanently?", resource); } @Override public void create() { super.create(); setTitle(title); setMessage(message, IMessageProvider.WARNING); getButton(IDialogConstants.OK_ID).setEnabled(false); } @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout layout = new GridLayout(1, false); container.setLayout(layout); createResourceNameSection(container); return area; } private void createResourceNameSection(Composite container) { new Label(container, SWT.NONE).setText(deleteResourceLabel); GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = SWT.FILL; resourceNameText = new Text(container, SWT.BORDER); resourceNameText.setLayoutData(gridData); resourceNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent event) { getButton(IDialogConstants.OK_ID).setEnabled(resourceName.equals(resourceNameText.getText())); } }); new Label(container, SWT.NONE).setText(deleteConfirmationLabel); } @Override protected boolean isResizable() { return true; } }
7,563
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/TagsEditingDialog.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import com.amazonaws.eclipse.core.model.KeyValueSetDataModel; import com.amazonaws.eclipse.core.ui.KeyValueSetEditingComposite.KeyValueSetEditingCompositeBuilder; import com.amazonaws.eclipse.core.validator.StringLengthValidator; public class TagsEditingDialog extends TitleAreaDialog { private final KeyValueSetDataModel dataModel; private final String title; private final String message; private final int maxKeyLength; private final int maxValueLength; private final SelectionListener saveListener; private TagsEditingDialog(Shell parentShell, KeyValueSetDataModel dataModel, String title, String message, int maxKeyLength, int maxValueLength, SelectionListener saveListener) { super(parentShell); this.dataModel = dataModel; this.title = title; this.message = message; this.maxKeyLength = maxKeyLength; this.maxValueLength = maxValueLength; this.saveListener = saveListener; } @Override public void create() { super.create(); setTitle(title); setMessage(message, IMessageProvider.INFORMATION); } @Override protected Control createDialogArea(Composite parent) { return new KeyValueSetEditingCompositeBuilder() .addKeyValidator(new StringLengthValidator(1, maxKeyLength, String.format("This field is too long. Maximum length is %d characters.", maxKeyLength))) .addValueValidator(new StringLengthValidator(0, maxValueLength, String.format("This field is too long. Maximum length is %d characters.", maxValueLength))) .saveListener(saveListener) .build(parent, dataModel); } @Override protected boolean isResizable() { return true; } public static class TagsEditingDialogBuilder { private String title = "Edit Tags"; private String message = "Tag objects to search, organize and manage access"; private int maxKeyLength = 128; private int maxValueLength = 256; private SelectionListener saveListener; public TagsEditingDialog build(Shell parentShell, KeyValueSetDataModel dataModel) { return new TagsEditingDialog(parentShell, dataModel, title, message, maxKeyLength, maxValueLength, saveListener); } public TagsEditingDialogBuilder title(String title) { this.title = title; return this; } public TagsEditingDialogBuilder message(String message) { this.message = message; return this; } public TagsEditingDialogBuilder maxKeyLength(int maxKeyLength) { this.maxKeyLength = maxKeyLength; return this; } public TagsEditingDialogBuilder maxValueLength(int maxValueLength) { this.maxValueLength = maxValueLength; return this; } public TagsEditingDialogBuilder saveListener(SelectionListener saveListener) { this.saveListener = saveListener; return this; } } }
7,564
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/SelectOrInputComposite.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import static com.amazonaws.eclipse.core.model.SelectOrInputDataModel.P_CREATE_NEW_RESOURCE; import static com.amazonaws.eclipse.core.model.SelectOrInputDataModel.P_EXISTING_RESOURCE; import static com.amazonaws.eclipse.core.model.SelectOrInputDataModel.P_NEW_RESOURCE_NAME; import static com.amazonaws.eclipse.core.model.SelectOrInputDataModel.P_SELECT_EXISTING_RESOURCE; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam; import com.amazonaws.eclipse.core.model.SelectOrInputDataModel; import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase; import com.amazonaws.eclipse.core.widget.RadioButtonComplex; import com.amazonaws.eclipse.core.widget.AwsResourceComboViewerComplex; import com.amazonaws.eclipse.core.widget.AwsResourceComboViewerComplex.AwsResourceComboViewerComplexBuilder; import com.amazonaws.eclipse.core.widget.AwsResourceComboViewerComplex.AwsResourceUiRefreshable; import com.amazonaws.services.lambda.model.AliasConfiguration; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.eclipse.core.widget.TextComplex; /** * A basic composite that includes a combo box, a text field and two radio buttons that could be used to select * a resource from the combo box, or create a new resource with the name in the text field. * * @param T - The underlying resource type, like {@link Bucket}. This is also the data type bound to the ComboBox. * @param K - The data model for this composite. * @param P - The resource loading scope for loading the specified AWS resource. For most of the AWS resources, * the {@link AwsResourceScopeParamBase} is sufficient which includes the account id and region id. But for * some resource like {@link AliasConfiguration}, additional restriction, function name in this case, is needed. */ public abstract class SelectOrInputComposite<T, K extends SelectOrInputDataModel<T, P>, P extends AbstractAwsResourceScopeParam<P>> extends Composite implements AwsResourceUiRefreshable<T> { private final DataBindingContext bindingContext; private final K dataModel; private final String selectResourceLabelValue; private final String createResourceLabelValue; private final List<IValidator> createTextValidators = new ArrayList<>(); private RadioButtonComplex selectRadioButton; private RadioButtonComplex createRadioButton; private AwsResourceComboViewerComplex<T, P> resourcesCombo; private TextComplex createText; private final NewResourceDoesNotExistValidator resourceNotExistsValidator = new NewResourceDoesNotExistValidator(); protected SelectOrInputComposite( Composite parent, DataBindingContext bindingContext, K dataModel, String selectResourceLabelValue, String createResourceLabelValue, List<IValidator> createTextValidators) { super(parent, SWT.NONE); this.bindingContext = bindingContext; this.dataModel = dataModel; this.selectResourceLabelValue = selectResourceLabelValue; this.createResourceLabelValue = createResourceLabelValue; this.createTextValidators.add(resourceNotExistsValidator); this.createTextValidators.addAll(createTextValidators); this.setLayout(new GridLayout(2, false)); this.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); createControls(); } /** * Refresh composite when changing any one of the parameters in the {@link AbstractAwsResourceScopeParam} */ public void refreshComposite(P param, String defaultResourceName) { resourcesCombo.refreshResources(param, defaultResourceName); } @Override public void refreshWhenLoadingError(List<T> resources) { selectRadioButton.setValue(false); createRadioButton.setValue(true); createText.setEnabled(isEnabled()); resourcesCombo.setEnabled(false); updateCreateTextValidator(resources); } @Override public void refreshWhenLoadingEmpty(List<T> resources) { selectRadioButton.setValue(false); createRadioButton.setValue(true); createText.setEnabled(isEnabled()); resourcesCombo.setEnabled(false); updateCreateTextValidator(resources); } @Override public void refreshWhenLoadingSuccess(List<T> resources) { createText.setEnabled(createRadioButton.getRadioButton().getSelection() && isEnabled()); resourcesCombo.setEnabled(selectRadioButton.getRadioButton().getSelection() && isEnabled()); updateCreateTextValidator(resources); } private void updateCreateTextValidator(List<T> resources) { resourceNotExistsValidator.setResources(resources); // A hacky way to set a random value to explicitly trigger the validation. createText.setText(UUID.randomUUID().toString()); createText.setText(dataModel.getDefaultResourceName()); } private void createControls() { this.selectRadioButton = RadioButtonComplex.builder() .composite(this) .dataBindingContext(bindingContext) .defaultValue(dataModel.isSelectExistingResource()) .labelValue(selectResourceLabelValue) .pojoObservableValue(PojoProperties.value(P_SELECT_EXISTING_RESOURCE, Boolean.class) .observe(dataModel)) .selectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onSelectRadioButtonSelected(); } }) .build(); this.resourcesCombo = new AwsResourceComboViewerComplexBuilder<T, P>() .composite(this) .bindingContext(bindingContext) .labelProvider(new LabelProvider() { @Override public String getText(Object element) { try { @SuppressWarnings("unchecked") T resource = (T) element; return dataModel.getResourceName(resource); } catch (ClassCastException cce) { // Do nothing } return super.getText(element); } }) .pojoObservableValue(PojoProperties.value(P_EXISTING_RESOURCE) .observe(dataModel)) .resourceMetadata(dataModel) .resourceUiRefresher(this) .build(); this.createRadioButton = RadioButtonComplex.builder() .composite(this) .dataBindingContext(bindingContext) .defaultValue(dataModel.isCreateNewResource()) .labelValue(createResourceLabelValue) .pojoObservableValue(PojoProperties.value(P_CREATE_NEW_RESOURCE, Boolean.class) .observe(dataModel)) .selectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onCreateRadioButtonSelected(); } }) .build(); this.createText = TextComplex.builder(this, bindingContext, PojoProperties.value(P_NEW_RESOURCE_NAME).observe(dataModel)) .createLabel(false) .addValidators(createTextValidators) .build(); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); this.selectRadioButton.getRadioButton().setEnabled(enabled); this.createRadioButton.getRadioButton().setEnabled(enabled); if (enabled) { onSelectRadioButtonSelected(); onCreateRadioButtonSelected(); } else { this.resourcesCombo.setEnabled(false); this.createText.setEnabled(false); } } private void onSelectRadioButtonSelected() { boolean selected = selectRadioButton.getRadioButton().getSelection(); this.resourcesCombo.setEnabled(isEnabled() && selected); this.createText.setEnabled(isEnabled() && !selected); } private void onCreateRadioButtonSelected() { boolean selected = createRadioButton.getRadioButton().getSelection(); this.resourcesCombo.setEnabled(isEnabled() && !selected); this.createText.setEnabled(isEnabled() && selected); } private final class NewResourceDoesNotExistValidator implements IValidator { private List<T> resources; public void setResources(List<T> resources) { this.resources = resources; } @Override public IStatus validate(Object value) { String resourceName = (String) value; T resource = dataModel.findResourceByName(resources, resourceName); return resource == null ? ValidationStatus.ok() : ValidationStatus.error(String.format("%s %s already exists.", dataModel.getResourceType(), resourceName)); } } }
7,565
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/AbstractTableLabelProvider.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.swt.graphics.Image; /** * No-op adapter class for table label providers. */ public abstract class AbstractTableLabelProvider implements ITableLabelProvider { @Override public void addListener(final ILabelProviderListener listener) { } @Override public void dispose() { } @Override public boolean isLabelProperty(final Object element, final String property) { return true; } @Override public void removeListener(final ILabelProviderListener listener) { } @Override public Image getColumnImage(final Object element, final int columnIndex) { return null; } @Override public String getColumnText(final Object element, final int columnIndex) { return null; } }
7,566
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/ProjectNameComposite.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import static com.amazonaws.eclipse.core.model.ProjectNameDataModel.P_PROJECT_NAME; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; 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.model.ProjectNameDataModel; import com.amazonaws.eclipse.core.validator.ProjectNameValidator; import com.amazonaws.eclipse.core.widget.TextComplex; /** * A reusable Project Name composite. */ public class ProjectNameComposite extends Composite { private TextComplex projectNameComplex; public ProjectNameComposite(Composite parent, DataBindingContext context, ProjectNameDataModel dataModel) { super(parent, SWT.NONE); setLayout(new GridLayout(2, false)); setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); createControl(context, dataModel); } private void createControl(DataBindingContext context, ProjectNameDataModel dataModel) { projectNameComplex = TextComplex.builder(this, context, PojoObservables.observeValue(dataModel, P_PROJECT_NAME)) .addValidator(new ProjectNameValidator()) .defaultValue(dataModel.getProjectName()) .labelValue("Project name:") .build(); } }
7,567
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/SelectOrCreateComposite.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import static com.amazonaws.eclipse.core.model.SelectOrInputDataModel.P_EXISTING_RESOURCE; import java.util.List; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; 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 com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam; import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase; import com.amazonaws.eclipse.core.model.SelectOrCreateDataModel; import com.amazonaws.eclipse.core.ui.dialogs.AbstractInputDialog; import com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory; import com.amazonaws.eclipse.core.widget.AwsResourceComboViewerComplex; import com.amazonaws.eclipse.core.widget.AwsResourceComboViewerComplex.AwsResourceComboViewerComplexBuilder; import com.amazonaws.eclipse.core.widget.AwsResourceComboViewerComplex.AwsResourceUiRefreshable; import com.amazonaws.services.lambda.model.AliasConfiguration; import com.amazonaws.services.s3.model.Bucket; /** * A basic composite that includes a label, a combo box and a button that could be used to select * a resource from the combo box, or create a new one by the button. * * @param T - The underlying resource type, like {@link Bucket}. This is also the data type bound to the ComboBox. * @param K - The data model for this composite. * @param P - The resource loading scope for loading the specified AWS resource. For most of the AWS resources, * the {@link AwsResourceScopeParamBase} is sufficient which includes the account id and region id. But for * some resource like {@link AliasConfiguration}, additional restriction, function name in this case, is needed. */ public abstract class SelectOrCreateComposite<T, K extends SelectOrCreateDataModel<T, P>, P extends AbstractAwsResourceScopeParam<P>> extends Composite implements AwsResourceUiRefreshable<T> { private final DataBindingContext bindingContext; private final K dataModel; private final String selectResourceLabelValue; private AwsResourceComboViewerComplex<T, P> resourcesCombo; private Button createButton; public SelectOrCreateComposite( Composite parent, DataBindingContext bindingContext, K dataModel, String selectResourceLabelValue) { super(parent, SWT.NONE); this.bindingContext = bindingContext; this.dataModel = dataModel; this.selectResourceLabelValue = selectResourceLabelValue; this.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); this.setLayout(new GridLayout(3, false)); createControls(); } public void refreshComposite(P param, String defaultResourceName) { resourcesCombo.refreshResources(param, defaultResourceName); } protected abstract AbstractInputDialog<T> createResourceDialog(P param); private void createControls() { this.resourcesCombo = new AwsResourceComboViewerComplexBuilder<T, P>() .composite(this) .bindingContext(bindingContext) .labelValue(selectResourceLabelValue) .pojoObservableValue(PojoProperties.value(P_EXISTING_RESOURCE).observe(dataModel)) .labelProvider(new LabelProvider() { @Override public String getText(Object element) { try { @SuppressWarnings("unchecked") T resource = (T) element; return dataModel.getResourceName(resource); } catch (ClassCastException cce) { return super.getText(element); } } }) .resourceMetadata(dataModel) .resourceUiRefresher(this) .build(); this.resourcesCombo.getComboViewer().getCombo().setEnabled(false); this.createButton = WizardWidgetFactory.newPushButton(this, "Create"); this.createButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onCreateButtonSelected(); } }); } private void onCreateButtonSelected() { AbstractInputDialog<T> dialog = createResourceDialog(resourcesCombo.getCurrentResourceScope()); int returnCode = dialog.open(); if (returnCode == Window.OK) { T newResource = dialog.getCreatedResource(); dataModel.setCreateNewResource(true); resourcesCombo.cacheNewResource(resourcesCombo.getCurrentResourceScope(), newResource); if (isEnabled() && !resourcesCombo.getComboViewer().getCombo().isEnabled()) { resourcesCombo.setEnabled(true); } } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); this.resourcesCombo.setEnabled(enabled); this.createButton.setEnabled(enabled); } @Override public void refreshWhenLoadingError(List<T> resources) { // Disable the combo box, but not disabling the enabler validator. resourcesCombo.getComboViewer().getCombo().setEnabled(false); } @Override public void refreshWhenLoadingEmpty(List<T> resources) { // Disable the combo box, but not disabling the enabler validator. resourcesCombo.getComboViewer().getCombo().setEnabled(false); } @Override public void refreshWhenLoadingSuccess(List<T> resources) { resourcesCombo.getComboViewer().getCombo().setEnabled(isEnabled()); } }
7,568
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/ManagementPerspectiveFactory.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.ui.IFolderLayout; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; public class ManagementPerspectiveFactory implements IPerspectiveFactory { /** Folder ID where the Amazon EC2 views will be opened */ private static final String BOTTOM_FOLDER_ID = "bottom"; /** Folder ID where the AWS Toolkit Overview will be opened */ private static final String LEFT_FOLDER_ID = "left"; /** Project Explorer view ID (not available through IPageLayout in 3.4) */ private static final String ORG_ECLIPSE_UI_NAVIGATOR_PROJECT_EXPLORER = "org.eclipse.ui.navigator.ProjectExplorer"; /** * The Package Explorer view from JDT. We create a placeholder for this * view, so that if a user has this view open in another perspective, * they'll see it here, too, otherwise they won't see it. */ private static final String JDT_PACKAGE_EXPLORER_VIEW_ID = "org.eclipse.jdt.ui.PackageExplorer"; @Override public void createInitialLayout(IPageLayout layout) { IFolderLayout left = layout.createFolder(LEFT_FOLDER_ID, IPageLayout.LEFT, 0.30f, layout.getEditorArea()); left.addView("com.amazonaws.eclipse.explorer.view"); left.addView(ORG_ECLIPSE_UI_NAVIGATOR_PROJECT_EXPLORER); left.addPlaceholder(JDT_PACKAGE_EXPLORER_VIEW_ID); IFolderLayout bot = layout.createFolder(BOTTOM_FOLDER_ID, IPageLayout.BOTTOM, 0.50f, layout.getEditorArea()); bot.addView(IPageLayout.ID_PROGRESS_VIEW); } }
7,569
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/ImportFileComposite.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import static com.amazonaws.eclipse.core.model.ImportFileDataModel.P_FILE_PATH; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newPushButton; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.dialogs.ContainerSelectionDialog; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.model.BaseWorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.model.ImportFileDataModel; import com.amazonaws.eclipse.core.validator.NoopValidator; import com.amazonaws.eclipse.core.widget.TextComplex; /** * A reusable File import widget composite. */ public class ImportFileComposite extends Composite { private TextComplex filePathComplex; private Button browseButton; private ImportFileComposite(Composite parent, DataBindingContext context, ImportFileDataModel dataModel, IValidator validator, String textLabel, String buttonLabel, ModifyListener modifyListener, String textMessage) { super(parent, SWT.NONE); setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); setLayout(new GridLayout(3, false)); createControl(context, dataModel, validator, textLabel, buttonLabel, modifyListener, textMessage); } @Override public void setEnabled(boolean enabled) { filePathComplex.setEnabled(enabled); browseButton.setEnabled(enabled); } @NonNull public static ImportFileCompositeBuilder builder( @NonNull Composite parent, @NonNull DataBindingContext dataBindingContext, @NonNull ImportFileDataModel dataModel) { return new ImportFileCompositeBuilder(parent, dataBindingContext, dataModel); } private void createControl(DataBindingContext context, ImportFileDataModel dataModel, IValidator filePathValidator, String textLabel, String buttonLabel, ModifyListener modifyListener, String textMessage) { filePathComplex = TextComplex.builder(this, context, PojoProperties.value(P_FILE_PATH).observe(dataModel)) .labelValue(textLabel) .addValidator(filePathValidator) .defaultValue(dataModel.getFilePath()) .modifyListener(modifyListener) .textMessage(textMessage) .build(); browseButton = newPushButton(this, buttonLabel); } public void setFilePath(String filePath) { filePathComplex.setText(filePath); } /** * The browse Button opens a general file selection dialog. */ private void setButtonListenerToBrowseFile() { browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(getShell(), SWT.SINGLE); String path = dialog.open(); if (path != null) { filePathComplex.setText(path); } } }); } /** * The browse Button opens a dialog to only allow to select folders under the workspace. */ private void setButtonListenerToBrowseWorkspaceDir() { browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, "Choose Base Directory"); dialog.showClosedProjects(false); int buttonId = dialog.open(); if (buttonId == IDialogConstants.OK_ID) { Object[] resource = dialog.getResult(); if (resource != null && resource.length > 0) { String fileLoc = VariablesPlugin.getDefault().getStringVariableManager() .generateVariableExpression("workspace_loc", ((IPath) resource[0]).toString()); filePathComplex.setText(fileLoc); } } } }); } /** * The browse Button opens a dialog to only allow to select files under the workspace. */ private void setButtonListenerToBrowseWorkspaceFile() { browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new BaseWorkbenchContentProvider()); dialog.setTitle("Choose File"); dialog.setInput(ResourcesPlugin.getWorkspace().getRoot()); int buttonId = dialog.open(); if (buttonId == IDialogConstants.OK_ID) { Object[] resource = dialog.getResult(); if (resource != null && resource.length > 0) { String fileLoc = VariablesPlugin.getDefault().getStringVariableManager() .generateVariableExpression("workspace_loc", ((IResource) resource[0]).getFullPath().toString()); filePathComplex.setText(fileLoc); } } } }); } /** * The browse Button opens a dialog to only allow to select project under the workspace. */ private void setButtonListenerToBrowseWorkspaceProject() { browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider); dialog.setTitle("Choose project"); dialog.setMessage("Choose the project for the job"); try { dialog.setElements(JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects()); } catch (JavaModelException jme) { AwsToolkitCore.getDefault().logError(jme.getMessage(), jme); } if (dialog.open() == Window.OK) { filePathComplex.setText(((IJavaProject) dialog.getFirstResult()).getElementName()); } } }); } public static final class ImportFileCompositeBuilder { private final Composite parent; private final DataBindingContext context; private final ImportFileDataModel dataModel; // Optional parameters private IValidator filePathValidator = new NoopValidator(); private ModifyListener modifyListener; private String textLabel = "Import:"; private String buttonLabel = "Browse"; private String textMessage = ""; private ImportFileCompositeBuilder( @NonNull Composite parent, @NonNull DataBindingContext context, @NonNull ImportFileDataModel dataModel) { this.parent = parent; this.context = context; this.dataModel = dataModel; } public ImportFileCompositeBuilder filePathValidator(IValidator filePathValidator) { this.filePathValidator = filePathValidator; return this; } public ImportFileCompositeBuilder textLabel(String textLabel) { this.textLabel = textLabel; return this; } public ImportFileCompositeBuilder buttonLabel(String buttonLabel) { this.buttonLabel = buttonLabel; return this; } public ImportFileCompositeBuilder modifyListener(ModifyListener modifyListener) { this.modifyListener = modifyListener; return this; } public ImportFileCompositeBuilder textMessage(String textMessage) { this.textMessage = textMessage; return this; } /** * Build a general file importer component. */ public ImportFileComposite build() { ImportFileComposite composite = new ImportFileComposite( parent, context, dataModel, filePathValidator, textLabel, buttonLabel, modifyListener, textMessage); composite.setButtonListenerToBrowseFile(); return composite; } public ImportFileComposite buildWorkspaceDirBrowser() { ImportFileComposite composite = new ImportFileComposite( parent, context, dataModel, filePathValidator, textLabel, buttonLabel, modifyListener, textMessage); composite.setButtonListenerToBrowseWorkspaceDir(); return composite; } public ImportFileComposite buildWorkspaceFileBrowser() { ImportFileComposite composite = new ImportFileComposite( parent, context, dataModel, filePathValidator, textLabel, buttonLabel, modifyListener, textMessage); composite.setButtonListenerToBrowseWorkspaceFile(); return composite; } public ImportFileComposite buildWorkspaceProjectBrowser() { ImportFileComposite composite = new ImportFileComposite( parent, context, dataModel, filePathValidator, textLabel, buttonLabel, modifyListener, textMessage); composite.setButtonListenerToBrowseWorkspaceProject(); return composite; } } }
7,570
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/EmailLinkListener.java
/* * Copyright 2008-2014 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import com.amazonaws.eclipse.core.diagnostic.utils.EmailMessageLauncher; /** * Implementation of Listener that launches an email client and opens up an * email message with the specified recipient, subject and content. */ public class EmailLinkListener implements Listener { private final EmailMessageLauncher launcher; public EmailLinkListener(final EmailMessageLauncher launcher) { this.launcher = launcher; } /* (non-Javadoc) * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event) */ @Override public void handleEvent(Event event) { launcher.open(); } }
7,571
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/SelectOrCreateBucketComposite.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase; import com.amazonaws.eclipse.core.model.SelectOrCreateBucketDataModel; import com.amazonaws.eclipse.core.ui.dialogs.AbstractInputDialog; import com.amazonaws.eclipse.core.ui.dialogs.CreateS3BucketDialog; import com.amazonaws.services.s3.model.Bucket; /** * A basic composite that includes a combo box and a button which could be used to select * a bucket from the combo box, or create a new one by the button. */ public class SelectOrCreateBucketComposite extends SelectOrCreateComposite<Bucket, SelectOrCreateBucketDataModel, AwsResourceScopeParamBase> { public SelectOrCreateBucketComposite( Composite parent, DataBindingContext bindingContext, SelectOrCreateBucketDataModel dataModel) { super(parent, bindingContext, dataModel, "S3 Bucket:"); } @Override protected AbstractInputDialog<Bucket> createResourceDialog(AwsResourceScopeParamBase param) { return new CreateS3BucketDialog(Display.getCurrent().getActiveShell(), param); } }
7,572
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/PreferenceLinkListener.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.dialogs.PreferencesUtil; /** * Simple Link listener that opens a link to a preference page. */ public class PreferenceLinkListener implements Listener { /** Optional Shell object to close after opening the link */ private Shell shellToClose; /** * Sets the Shell object that should be closed after a link is opened. * * @param shell * The Shell to close after opening the selected link. */ public void setShellToClose(Shell shell) { shellToClose = shell; } /* (non-Javadoc) * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event) */ @Override public void handleEvent(Event event) { String preferencePage = event.text; if (shellToClose != null) { shellToClose.close(); } PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn( null, preferencePage, new String[] {preferencePage}, null); dialog.open(); } }
7,573
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/RegionSelectionComposite.java
package com.amazonaws.eclipse.core.ui; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; /** * @deprecated for {@link RegionComposite} */ @Deprecated public class RegionSelectionComposite extends Composite { private String serviceName; private Combo regionSelectionCombo; private List<SelectionListener> listeners = new ArrayList<>(); public RegionSelectionComposite(final Composite parent, final int style) { this(parent, style, null); } public void addSelectionListener(SelectionListener listener) { this.listeners.add(listener); } public RegionSelectionComposite(final Composite parent, final int style, final String serviceName) { super(parent, style); this.serviceName = serviceName; this.setLayout(new GridLayout(3, false)); createRegionSelectionCombo(); } protected void createRegionSelectionCombo() { Label selectAccount = new Label(this, SWT.None); selectAccount.setText("Select Region:"); //$NON-NLS-1$ regionSelectionCombo = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY); List<Region> regions = serviceName == null ? RegionUtils.getRegions() : RegionUtils.getRegionsForService(serviceName); for (Region region : regions) { regionSelectionCombo.add(region.getName()); regionSelectionCombo.setData(region.getName(), region); } regionSelectionCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for ( SelectionListener listener : listeners ) { listener.widgetSelected(e); } } }); } public void setSelectRegion(String regionName) { regionSelectionCombo.setText(regionName); } public String getSelectedRegion() { return ((Region)regionSelectionCombo.getData(regionSelectionCombo.getText())).getId(); } public void setSelection(int index) { int itemCount = regionSelectionCombo.getItemCount(); if (index < 0 || index > itemCount - 1) { throw new IllegalArgumentException("The index provided is invalid!"); } regionSelectionCombo.select(index); } }
7,574
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/MultiValueEditorDialog.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; 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.Listener; import org.eclipse.swt.widgets.Shell; 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 com.amazonaws.eclipse.core.AwsToolkitCore; /** * Simple table dialog to allow use user to enter multiple values for an * attribute. */ public class MultiValueEditorDialog extends MessageDialog { private static final String NEW_VALUE = "<new value>"; private boolean editLocked = false; private int lockedRowIndex = -1; protected final List<String> values = new ArrayList<>(); protected String columnText = "Attributes"; public List<String> getValues() { return this.values; } protected TableViewer tableViewer; /** * Default constructor provides "OK" and "Cancel" buttons with an AWS logo. */ public MultiValueEditorDialog(final Shell parentShell) { super(parentShell, "Edit values", AwsToolkitCore.getDefault().getImageRegistry() .get(AwsToolkitCore.IMAGE_AWS_ICON), "", MessageDialog.NONE, new String[] { "OK", "Cancel" }, 0); } /** * Full featured constructor from {@link MessageDialog} */ public MultiValueEditorDialog(Shell parentShell, String dialogTitle, Image dialogTitleImage, String dialogMessage, int dialogImageType, String[] dialogButtonLabels, int defaultIndex) { super(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, dialogButtonLabels, defaultIndex); } @Override protected boolean isResizable() { return true; } @Override protected Control createDialogArea(final Composite parent) { Composite composite = new Composite(parent, SWT.None); GridDataFactory.fillDefaults().grab(true, true).span(2, 1).applyTo(composite); TableColumnLayout layout = new TableColumnLayout(); composite.setLayout(layout); this.tableViewer = new TableViewer(composite); this.tableViewer.getTable().setHeaderVisible(true); TableColumn tableColumn = new TableColumn(this.tableViewer.getTable(), SWT.NONE); tableColumn.setText(columnText); layout.setColumnData(tableColumn, new ColumnWeightData(100)); this.tableViewer.setContentProvider(new AbstractTableContentProvider() { @Override public Object[] getElements(final Object inputElement) { Object[] rowsPlusNew = new Object[MultiValueEditorDialog.this.values.size() + 1]; MultiValueEditorDialog.this.values.toArray(rowsPlusNew); rowsPlusNew[rowsPlusNew.length - 1] = NEW_VALUE; return rowsPlusNew; } }); this.tableViewer.setLabelProvider(new AbstractTableLabelProvider() { @Override public String getColumnText(final Object element, final int columnIndex) { return (String) element; } }); final Table table = this.tableViewer.getTable(); final TableEditor editor = new TableEditor(table); editor.horizontalAlignment = SWT.LEFT; editor.grabHorizontal = true; table.addListener(SWT.MouseUp, new Listener() { @Override public void handleEvent(final Event event) { Rectangle clientArea = table.getClientArea(); Point pt = new Point(event.x, event.y); int index = table.getTopIndex(); while ( index < table.getItemCount() ) { boolean visible = false; final TableItem item = table.getItem(index); // Only one column, but loop is here for completeness for ( int i = 0; i < table.getColumnCount(); i++ ) { Rectangle rect = item.getBounds(i); if ( rect.contains(pt) ) { final int column = i; final Text text = new Text(table, SWT.NONE); final int idx = index; if ( isRowUneditable(idx) ) { return; } Listener textListener = new Listener() { @Override public void handleEvent(final Event e) { if ( e.type == SWT.Traverse && e.detail == SWT.TRAVERSE_ESCAPE ) { /* Skip data validation and dispose the text editor */ text.dispose(); e.doit = false; return; } else if ( e.type == SWT.Traverse && e.detail != SWT.TRAVERSE_RETURN ) { /* No-op for keys other than escape or return. */ return; } else { /* For all other events, we first validate the data */ if ( !validateAttributeValue(text.getText()) ) { lockTableEditor(idx); return; } /* First unlock everything */ unlockTableEditor(); /* Then we handle different events */ if ( e.type == SWT.FocusOut ) { modifyValue(item, column, idx, text); text.dispose(); } else if ( e.type == SWT.Traverse && e.detail == SWT.TRAVERSE_RETURN ) { modifyValue(item, column, idx, text); } else if ( e.type == SWT.Modify ) { /* No-op */ } } } }; text.addListener(SWT.FocusOut, textListener); text.addListener(SWT.Traverse, textListener); text.addListener(SWT.Modify, textListener); editor.setEditor(text, item, i); text.setText(item.getText(i)); text.selectAll(); text.setFocus(); return; } if ( !visible && rect.intersects(clientArea) ) { visible = true; } } if ( !visible ) { return; } index++; } } }); /* Suppress changing to other table rows when the editor is locked. */ this.tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { private boolean update = true; private ISelection lastSelection; @Override public void selectionChanged(SelectionChangedEvent event) { if ( update && isLocked() ) { update = false; // avoid infinite loop tableViewer.setSelection(lastSelection); update = true; } else if ( !isLocked() ) { lastSelection = event.getSelection(); } } }); this.tableViewer.setInput(values.size()); this.tableViewer.getTable().getItem(this.values.size()) .setForeground(Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY)); return composite; } /** * Called when a value in the list is modified. */ protected void modifyValue(final TableItem item, final int column, final int index, final Text text) { String newValue = text.getText(); if ( newValue.length() == 0 ) { if ( index < this.values.size() ) { this.values.remove(index); } this.tableViewer.refresh(); } else { item.setText(column, newValue); if ( index == item.getParent().getItemCount() - 1 ) { this.values.add(newValue); this.tableViewer.refresh(); item.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK)); this.tableViewer.getTable().getItem(this.values.size()) .setForeground(Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY)); } else { this.values.set(index, newValue); } } } /** * Base class always returns true when validating the data. */ protected boolean validateAttributeValue(String attributeValue) { return true; } /** * Add a customized suffix for the column text. */ protected void addColumnTextDescription(String columnTextSuffix) { this.columnText = this.columnText + " " + columnTextSuffix; } /** * @param index * The index of the locked row. */ protected void lockTableEditor(int index) { editLocked = true; lockedRowIndex = index; this.getButton(0).setEnabled(false); this.getButtonBar().update(); } protected void unlockTableEditor() { editLocked = false; lockedRowIndex = -1; this.getButton(0).setEnabled(true); this.getButtonBar().update(); } private boolean isLocked() { return editLocked; } private boolean isRowUneditable(int index) { return editLocked && index != lockedRowIndex; } }
7,575
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/Startup.java
/* * Copyright 2009-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPersistableElement; import org.eclipse.ui.IStartup; import org.eclipse.ui.IWorkbenchWindow; 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; /** * Runs at startup to determine if any new AWS Toolkit components have been * installed, and if so, displays the AWS Toolkit Overview view. */ public class Startup implements IStartup { private static IEditorInput input = null; /* (non-Javadoc) * @see org.eclipse.ui.IStartup#earlyStartup() */ @Override public void earlyStartup() { recordOverviewContributors(); } /* * Protected Interface */ /** * Returns true if the AWS Toolkit Overview view should be displayed. * * @return True if the AWS Toolkit Overview view should be displayed. */ protected boolean shouldDisplayOverview() { Map<String, String> overviewContributors = findOverviewContributors(); Map<String, String> registeredOverviewContributors = getRegisteredOverviewContributors(); // If we found more overview contributors than we have registered, // we know something must be new so we can return early. if (overviewContributors.size() > registeredOverviewContributors.size()) { return true; } for (String key : overviewContributors.keySet()) { /* * If we identified a contributing plugin that hasn't been * registered yet, we want to display the overview view. */ if (!registeredOverviewContributors.containsKey(key)) { return true; } } return false; } /** * Opens the AWS Toolkit Overview editor. */ protected static void displayAwsToolkitOverviewEditor() { if ( input == null) { input = new IEditorInput() { @Override public Object getAdapter(Class adapter) { return null; } @Override public String getToolTipText() { return "AWS Toolkit for Eclipse Overview"; } @Override public IPersistableElement getPersistable() { return null; } @Override public String getName() { return "AWS Toolkit for Eclipse Overview"; } @Override public ImageDescriptor getImageDescriptor() { return null; } @Override public boolean exists() { return true; } }; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); activeWindow.getActivePage().openEditor(input, AwsToolkitCore.OVERVIEW_EDITOR_ID); AwsAction.publishSucceededAction(AwsToolkitMetricType.OVERVIEW); } catch (PartInitException e) { AwsAction.publishFailedAction(AwsToolkitMetricType.OVERVIEW); AwsToolkitCore.getDefault().logError("Unable to open the AWS Toolkit Overview view.", e); } } }); } /* * Private Interface */ /** * Returns the file which records which components of the AWS Toolkit for * Eclipse are installed. * * @return The file which records which components of the AWS Toolkit for * Eclipse are installed. */ private File getPropertiesFile() { return AwsToolkitCore.getDefault().getBundle().getBundleContext().getDataFile("awsToolkitInstalledPlugins.properties"); } /** * Returns a map of plugin versions, keyed by their plugin ID, representing * plugins that have previously been detected and recorded as contributing * to the AWS Toolkit Overview view. * * @return A map of plugin versions, keyed by their plugin ID, representing * plugins that have been recorded as contributing to the AWS * Toolkit Overview view. */ private Map<String, String> getRegisteredOverviewContributors() { Map<String, String> registeredPlugins = new HashMap<>(); File dataFile = getPropertiesFile(); if (dataFile == null || dataFile.exists() == false) { return registeredPlugins; } try (InputStream inputStream = new FileInputStream(dataFile)) { Properties properties = new Properties(); properties.load(inputStream); for (Object key : properties.keySet()) { String value = properties.getProperty(key.toString()); registeredPlugins.put(key.toString(), value); } } catch (IOException e) { AwsToolkitCore.getDefault().logError("Unable to read currently registered AWS Toolkit components.", e); } return registeredPlugins; } /** * Returns a map of plugin versions, keyed by their plugin ID, representing * installed plugins which contribute to the AWS Toolkit Overview view * through the core plugin's extension point. * * @return A map of plugin versions, keyed by their plugin ID, representing * installed plugins which contribute to the AWS Toolkit Overview * view. */ private Map<String, String> findOverviewContributors() { Map<String, String> plugins = new HashMap<>(); IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(AwsToolkitCore.OVERVIEW_EXTENSION_ID); IExtension[] extensions = extensionPoint.getExtensions(); for (IExtension extension : extensions) { String pluginName = extension.getContributor().getName(); Dictionary headers = Platform.getBundle(pluginName).getHeaders(); String pluginVersion = (String)headers.get("Bundle-Version"); if (pluginVersion == null) pluginVersion = ""; plugins.put(pluginName, pluginVersion); } return plugins; } /** * Records a list of the detected plugins (and their versions) which * contribute to the AWS Toolkit Overview view through the core plugin's * overview extension point. */ private void recordOverviewContributors() { File dataFile = getPropertiesFile(); Properties properties = new Properties(); Map<String, String> contributions = findOverviewContributors(); for (String pluginName : contributions.keySet()) { String pluginVersion = contributions.get(pluginName); properties.put(pluginName, pluginVersion); } try (OutputStream outputStream = new FileOutputStream(dataFile)) { properties.store(outputStream, null); } catch (IOException e) { AwsToolkitCore.getDefault().logError("Unable to record registered components.", e); } } }
7,576
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/AbstractTableContentProvider.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.Viewer; /** * Simple no-op adapter class for content providers. */ public abstract class AbstractTableContentProvider implements IStructuredContentProvider { @Override public void dispose() { // TODO Auto-generated method stub } @Override public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { } @Override public Object[] getElements(final Object inputElement) { return null; } }
7,577
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/IRefreshable.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; /** * Simple interface to tag controls so that callers can request they refresh the * data they are displaying. */ public interface IRefreshable { /** * Refreshes the data displayed by this IRefreshable control. */ public void refreshData(); }
7,578
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/CancelableThread.java
/* * Copyright 2010-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; /** * Thread with running and canceled information, meant for background tasks * where the work will often be discarded and restarted. Subclasses should make * sure to set isRunning to false when their work is done, and to not do any * potentially conflicting work if isCanceled is true. */ public abstract class CancelableThread extends Thread { protected boolean running = true; protected boolean canceled = false; public synchronized final boolean isRunning() { return running; } public synchronized final void setRunning(boolean running) { this.running = running; } /** * Subclasses shouldn't do any potentially conflicting UI work before * checking to see if the thread has been canceled. */ public synchronized final boolean isCanceled() { return canceled; } public synchronized final void cancel() { this.canceled = true; } /** * Cancels the thread given if it's running. */ public static void cancelThread(CancelableThread thread) { if ( thread != null ) { synchronized ( thread ) { if ( thread.isRunning() ) { thread.cancel(); } } } } }
7,579
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/DisplayAwsOverviewEditorCmdHandler.java
/* * Copyright 2009-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; /** * Command Handler to open AWS Toolkit Overview Editor. */ public class DisplayAwsOverviewEditorCmdHandler extends AbstractHandler { /* * @see org.eclipse.core.commands.IHandler#execute(ExecutionEvent) */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { Startup.displayAwsToolkitOverviewEditor(); return null; } }
7,580
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences/RegionsPreferencePage.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.ui.WebLinkListener; /** * Preference page for AWS region preferences. */ public class RegionsPreferencePage extends AwsToolkitPreferencePage implements IWorkbenchPreferencePage { /** Combo box allowing the user to override the default AWS region */ private Combo regionsCombo; /** * Constructs a RegionPreferencesPage and sets the title and description. */ public RegionsPreferencePage() { super("Region Preferences"); this.setPreferenceStore(AwsToolkitCore.getDefault().getPreferenceStore()); this.setDescription("Region Preferences"); } /* (non-Javadoc) * @see org.eclipse.jface.preference.PreferencePage#performOk() */ @Override public boolean performOk() { String regionId = (String)regionsCombo.getData(regionsCombo.getText()); getPreferenceStore().setValue(PreferenceConstants.P_DEFAULT_REGION, regionId); return super.performOk(); } /* (non-Javadoc) * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) */ @Override protected Control createContents(Composite parent) { Composite composite = new Composite(parent, SWT.LEFT); composite.setLayout(new GridLayout()); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); WebLinkListener webLinkListener = new WebLinkListener(); createRegionSection(composite, webLinkListener); createSpacer(composite); return composite; } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ @Override public void init(IWorkbench workbench) {} /** * Creates the region section in this preference page. * * @param parent * The parent composite in which the region section should be * placed. * @param webLinkListener * The link listener to use for any Links. */ private void createRegionSection(Composite parent, WebLinkListener webLinkListener) { Group regionGroup = newGroup("Regions:", parent); String regionsHelpLinkText = "AWS regions allow you to position your AWS resources in different geographical areas, " + "enabling you to keep your application's data close to your customers, and add redundancy to your system, since " + "each region is isolated from each other.\n"; newLink(webLinkListener, regionsHelpLinkText, regionGroup); Label label = new Label(regionGroup, SWT.NONE); label.setText("Default Region:"); regionsCombo = new Combo(regionGroup, SWT.DROP_DOWN | SWT.READ_ONLY); regionsCombo.removeAll(); String currentDefaultRegionId = getPreferenceStore().getString(PreferenceConstants.P_DEFAULT_REGION); for (Region region : RegionUtils.getRegions()) { regionsCombo.add(region.getName()); regionsCombo.setData(region.getName(), region.getId()); if (currentDefaultRegionId.equals(region.getId())) { regionsCombo.setText(region.getName()); } } if (regionsCombo.getText() == null || regionsCombo.getText().length() == 0) { regionsCombo.select(0); } GridData gridData = new GridData(); gridData.horizontalSpan = 2; regionsCombo.setLayoutData(gridData); tweakLayout((GridLayout)regionGroup.getLayout()); } }
7,581
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences/AwsAccountPreferencePage.java
/* * Copyright 2008-2014 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.preferences; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.BooleanFieldEditor; import org.eclipse.jface.preference.FileFieldEditor; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.IntegerFieldEditor; 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.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.Link; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import com.amazonaws.eclipse.core.AccountInfo; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.AwsUrls; import com.amazonaws.eclipse.core.accounts.AwsPluginAccountManager; import com.amazonaws.eclipse.core.diagnostic.utils.EmailMessageLauncher; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.ui.EmailLinkListener; import com.amazonaws.eclipse.core.ui.PreferenceLinkListener; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.eclipse.core.ui.overview.Toolkit; import com.amazonaws.util.StringUtils; /** * Preference page for basic AWS account information. */ public class AwsAccountPreferencePage extends AwsToolkitPreferencePage implements IWorkbenchPreferencePage { public static final String ID = "com.amazonaws.eclipse.core.ui.preferences.AwsAccountPreferencePage"; private static final int PREFERRED_PAGE_WIDTH = 800; private TabFolder accountsTabFolder; /** * Map of all the account info, keyed by account identifier. This map * instance is shared by all the tabs, so that they have the synchronized * views over the configured accounts. This map is updated in-memory * whenever any account is added/removed/modified, and it will only be saved * in the external source when {@link #performOk()} is called. Note that the * accounts deleted in the preference page will only be removed from this * map; the actual deletion in the external source is handled separately. */ private final LinkedHashMap<String, AccountInfo> accountInfoByIdentifier = new LinkedHashMap<>(); /** * All the accounts that are to be deleted. */ private final Set<AccountInfo> accountInfoToBeDeleted = new HashSet<>(); private FileFieldEditor credentailsFileLocation; private boolean credentailsFileLocationChanged = false; private BooleanFieldEditor alwaysReloadWhenCredFileChanged; private IntegerFieldEditor connectionTimeout; private IntegerFieldEditor socketTimeout; private Font italicFont; /** * Creates the preference page and connects it to the plugin's preference * store. */ public AwsAccountPreferencePage() { super("AWS Toolkit Preferences"); setPreferenceStore(AwsToolkitCore.getDefault().getPreferenceStore()); setDescription("AWS Toolkit Preferences"); } /* * Public static methods for retrieving/updating account configurations * from/to the preference store */ /** * Returns whether the given region is configured with region-specific * default accounts and that the configuration is not disabled. */ public static boolean isRegionDefaultAccountEnabled(IPreferenceStore preferenceStore, Region region) { boolean configured = getRegionsWithDefaultAccounts(preferenceStore) .contains(region.getId()); // getBoolean(...) method returns false when the property is not specified. // We use isDefault(...) instead so that only an explicit "false" // indicates the region accounts are disabled. boolean enabled = preferenceStore.isDefault( PreferenceConstants.P_REGION_DEFAULT_ACCOUNT_ENABLED(region)); return configured && enabled; } /** * Returns the default account id associated with the given region. If the * region is not configured with default accounts, then this method returns * the global account id. */ public static String getDefaultAccountByRegion(IPreferenceStore preferenceStore, Region region) { if (isRegionDefaultAccountEnabled(preferenceStore, region)) { return preferenceStore.getString(PreferenceConstants.P_REGION_CURRENT_DEFAULT_ACCOUNT(region)); } else { return preferenceStore.getString(PreferenceConstants.P_GLOBAL_CURRENT_DEFAULT_ACCOUNT); } } /** * Returns list of region ids that are configured with region-specific * default accounts, no matter enabled or not. */ public static List<String> getRegionsWithDefaultAccounts(IPreferenceStore preferenceStore) { String regionIdsString = preferenceStore.getString(PreferenceConstants.P_REGIONS_WITH_DEFAULT_ACCOUNTS); if (regionIdsString == null || regionIdsString.isEmpty()) { return Collections.emptyList(); } String[] regionIds = regionIdsString.split(PreferenceConstants.REGION_ID_SEPARATOR_REGEX); return Arrays.asList(regionIds); } /** * Utility function that recursively enable/disable all the children * controls contained in the given Composite. */ static void setEnabledOnAllChildern(Composite composite, boolean enabled) { if (composite == null) return; for (Control child : composite.getChildren()) { if (child instanceof Composite) { setEnabledOnAllChildern((Composite) child, enabled); } child.setEnabled(enabled); } } /* * PreferencePage Interface */ /* * (non-Javadoc) * * @see * org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ @Override public void init(IWorkbench workbench) {} /* * (non-Javadoc) * * @see * org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse * .swt.widgets.Composite) */ @Override protected Control createContents(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout()); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.widthHint = PREFERRED_PAGE_WIDTH; composite.setLayoutData(gridData); // Accounts section createAccountsSectionGroup(composite); // Credentials file location section createCredentialsFileGroup(composite); // Timeouts section createTimeoutSectionGroup(composite); // The weblinks at the bottom part of the page createFeedbackSection(composite); parent.pack(); return composite; } /** * This method persists the value of P_REGIONS_WITH_DEFAULT_ACCOUNTS property, * according to the current configuration of this preference page. */ private void markRegionsWithDefaultAccount(IPreferenceStore preferenceStore, List<String> regionIds) { String regionIdsString = StringUtils.join(PreferenceConstants.REGION_ID_SEPARATOR, regionIds.toArray(new String[regionIds.size()])); preferenceStore.setValue(PreferenceConstants.P_REGIONS_WITH_DEFAULT_ACCOUNTS, regionIdsString); } /** * Returns the ids of all the regions that are configured with an account tab */ private List<String> getConfiguredRegions() { List<String> regionIds = new LinkedList<>(); for (TabItem tab : accountsTabFolder.getItems()) { if (tab instanceof AwsAccountPreferencePageTab) { AwsAccountPreferencePageTab accountTab = (AwsAccountPreferencePageTab) tab; if ( !accountTab.isGlobalAccoutTab() ) { regionIds.add(accountTab.getRegion().getId()); } } } return Collections.unmodifiableList(regionIds); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.PreferencePage#performDefaults() */ @Override protected void performDefaults() { // Load default preference values for the current account tab. if (accountsTabFolder != null && accountsTabFolder.getSelectionIndex() != -1) { TabItem tab = accountsTabFolder.getItem(accountsTabFolder.getSelectionIndex()); if (tab instanceof AwsAccountPreferencePageTab) { ((AwsAccountPreferencePageTab) tab).loadDefault(); } } if (credentailsFileLocation != null) { credentailsFileLocation.loadDefault(); } if (alwaysReloadWhenCredFileChanged != null) { alwaysReloadWhenCredFileChanged.loadDefault(); } if (connectionTimeout != null) { connectionTimeout.loadDefault(); } if (socketTimeout != null) { socketTimeout.loadDefault(); } super.performDefaults(); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.PreferencePage#performOk() */ @Override public boolean performOk() { try { // Don't support changing credentials file location and editing the // account infomration at the same time. if ( !credentailsFileLocationChanged && accountsTabFolder != null ) { /* Save the AccountInfo instances to the external source */ saveAccounts(); /* Persist the metadata in the preference store */ // credentialProfileAccountIds=accoutId1|accountId2 AwsToolkitCore.getDefault() .getAccountManager().getAccountInfoProvider() .updateProfileAccountMetadataInPreferenceStore( accountInfoByIdentifier.values()); // regionsWithDefaultAccounts=region1|region2 List<String> configuredRegions = getConfiguredRegions(); markRegionsWithDefaultAccount(getPreferenceStore(), configuredRegions); /* Call doStore on each tab. */ for (TabItem tab : accountsTabFolder.getItems()) { if (tab instanceof AwsAccountPreferencePageTab) { ((AwsAccountPreferencePageTab) tab).doStore(); } } } if (credentailsFileLocation != null) { credentailsFileLocation.store(); } if (alwaysReloadWhenCredFileChanged != null) { alwaysReloadWhenCredFileChanged.store(); } AwsToolkitCore.getDefault().getAccountManager().reloadAccountInfo(); if (connectionTimeout != null) { connectionTimeout.store(); } if (socketTimeout != null) { socketTimeout.store(); } return super.performOk(); } catch (Exception e) { AwsToolkitCore.getDefault().reportException("Internal error when saving account preference configurations.", e); return false; } } /** * Check for duplicate account names. */ public void updatePageValidationOfAllTabs() { for (TabItem tab : accountsTabFolder.getItems()) { if (tab instanceof AwsAccountPreferencePageTab) { AwsAccountPreferencePageTab accountTab = (AwsAccountPreferencePageTab)tab; // Early termination if any of the tab is invalid if (accountTab.updatePageValidation()) { return; } } } setValid(true); setErrorMessage(null); } @Override public void dispose() { if (italicFont != null) italicFont.dispose(); super.dispose(); } List<AwsAccountPreferencePageTab> getAllAccountPreferencePageTabs() { List<AwsAccountPreferencePageTab> tabs = new LinkedList<>(); for (TabItem tab : accountsTabFolder.getItems()) { if (tab instanceof AwsAccountPreferencePageTab) { tabs.add((AwsAccountPreferencePageTab)tab); } } return tabs; } /** * Package-private method that returns the map of all the configured * accounts. */ LinkedHashMap<String, AccountInfo> getAccountInfoByIdentifier() { return accountInfoByIdentifier; } /** * Package-private method that returns the set of all the accounts that are * to be deleted. */ Set<AccountInfo> getAccountInfoToBeDeleted() { return accountInfoToBeDeleted; } 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 Interface */ /** * Load all the configured accounts and clear accountInfoToBeDeleted. */ private void initAccountInfo() { AwsPluginAccountManager accountManager = AwsToolkitCore.getDefault().getAccountManager(); accountInfoByIdentifier.clear(); accountInfoByIdentifier.putAll(accountManager.getAllAccountInfo()); accountInfoToBeDeleted.clear(); } private void createAccountsSectionGroup(final Composite parent) { final Composite composite = new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); composite.setLayout(new GridLayout()); initAccountInfo(); // If empty, simply add an error label if (accountInfoByIdentifier.isEmpty()) { new Label(composite, SWT.READ_ONLY) .setText(String .format("Failed to load credential profiles from (%s).%n" + "Please check that your credentials file is in the correct format.", getPreferenceStore() .getString(PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION))); return; } // A TabFolder containing the following tabs: // Global Account | region-1 | region-2 | ... | + Configure Regional Account final TabFolder tabFolder = new TabFolder(composite, SWT.BORDER); tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tabFolder.pack(); int tabIndex = 0; // Global default accounts @SuppressWarnings("unused") final AwsAccountPreferencePageTab globalAccountTab = new AwsAccountPreferencePageTab( tabFolder, tabIndex, this, null); // Region default accounts for (String regionId : getRegionsWithDefaultAccounts(getPreferenceStore())) { Region configuredRegion = RegionUtils.getRegion(regionId); if (configuredRegion != null) { new AwsAccountPreferencePageTab( tabFolder, ++tabIndex, this, configuredRegion); } } // The fake tab for "Add default accounts for a region" final TabItem newRegionalAccountConfigTab = new TabItem(tabFolder, SWT.NONE); newRegionalAccountConfigTab.setToolTipText("Configure Regional Account"); newRegionalAccountConfigTab.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD)); tabFolder.addSelectionListener(new SelectionAdapter() { int lastSelection = 0; @Override public void widgetSelected(SelectionEvent e) { if (e.item == newRegionalAccountConfigTab) { // Suppress selection on the fake tab tabFolder.setSelection(lastSelection); // Prompt up the region selection dialog RegionSelectionDialog dialog = new RegionSelectionDialog(); int regionSelected = dialog.open(); if (regionSelected == 1) { Region selectedRegion = dialog.getSelectedRegion(); // Search for the selectedRegion from the existing tabs for (int ind = 0; ind < tabFolder.getItemCount(); ind++) { TabItem tab = tabFolder.getItem(ind); if (tab instanceof AwsAccountPreferencePageTab) { Region tabRegion = ((AwsAccountPreferencePageTab) tab).getRegion(); if (tabRegion != null && tabRegion.getId().equals(selectedRegion.getId())) { tabFolder.setSelection(ind); return; } } } // Create a new tab for the selected region if it's not found @SuppressWarnings("unused") AwsAccountPreferencePageTab newRegionAccountTab = new AwsAccountPreferencePageTab( tabFolder, tabFolder.getItemCount() - 1, // before the "new regional account" tab AwsAccountPreferencePage.this, selectedRegion); tabFolder.setSelection(tabFolder.getItemCount() - 2); // Select the newly created tab } } else { // Keep track of the latest selected tab lastSelection = tabFolder.getSelectionIndex(); } } }); this.accountsTabFolder = tabFolder; } /** * We currently don't support changing the credentials file location and * editing the account information at the same time. */ private Group createCredentialsFileGroup(final Composite parent) { Group group = new Group(parent, SWT.NONE); group.setText("Credentials file:"); group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); GridLayout groupLayout = new GridLayout(); groupLayout.marginWidth = 20; group.setLayout(groupLayout); final Label credentialsFileLocationLabel = new Label(group, SWT.WRAP); credentialsFileLocationLabel .setText("The location of the credentials file where " + "all your configured profiles will be persisted."); setItalicFont(credentialsFileLocationLabel); final Composite composite = new Composite(group, SWT.NONE); GridData data = new GridData(SWT.FILL, SWT.TOP, true, false); composite.setLayoutData(data); credentailsFileLocation = new FileFieldEditor( PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION, "Credentials file:", true, composite); credentailsFileLocation.setPage(this); credentailsFileLocation.setPreferenceStore(getPreferenceStore()); credentailsFileLocation.load(); if (accountsTabFolder != null) { credentailsFileLocation.getTextControl(composite).addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { String modifiedLocation = credentailsFileLocation .getTextControl(composite).getText(); // We only allow account info editing if the // credentials file location is unchanged. if (modifiedLocation.equals( getPreferenceStore().getString( PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION))) { setEnabledOnAllChildern(accountsTabFolder, true); updatePageValidationOfAllTabs(); } else { credentailsFileLocationChanged = true; setEnabledOnAllChildern(accountsTabFolder, false); File newCredFile = new File(modifiedLocation); if ( !newCredFile.exists() ) { setValid(false); setErrorMessage("Credentials file does not exist at the specified location."); } } } }); for (TabItem tab : accountsTabFolder.getItems()) { if (tab instanceof AwsAccountPreferencePageTab) { AwsAccountPreferencePageTab accountTab = (AwsAccountPreferencePageTab)tab; accountTab.addAccountInfoFieldEditorModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent arg0) { for (AccountInfo account : accountInfoByIdentifier.values()) { if (account.isDirty()) { // Disable the credential file location // editor when the account info section // is modified. setEnabledOnAllChildern(composite, false); } } } }); } } } Composite secondRow = new Composite(composite, SWT.NONE); GridData secondRowGridData = new GridData(SWT.FILL, SWT.TOP, true, false); secondRowGridData.horizontalSpan = 3; // file editor takes 3 columns secondRow.setLayoutData(secondRowGridData); alwaysReloadWhenCredFileChanged = new BooleanFieldEditor( PreferenceConstants.P_ALWAYS_RELOAD_WHEN_CREDNENTIAL_PROFILE_FILE_MODIFIED, "Automatically reload accounts when the credentials file is modified in the file system.", secondRow); alwaysReloadWhenCredFileChanged.setPage(this); alwaysReloadWhenCredFileChanged.setPreferenceStore(getPreferenceStore()); alwaysReloadWhenCredFileChanged.load(); return group; } private Group createTimeoutSectionGroup(final Composite parent) { Group group = new Group(parent, SWT.NONE); group.setText("Timeouts:"); group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); group.setLayout(new GridLayout(2, false)); Composite composite = new Composite(group, SWT.NONE); GridData data = new GridData(SWT.FILL, SWT.TOP, false, false); composite.setLayoutData(data); connectionTimeout = new IntegerFieldEditor( PreferenceConstants.P_CONNECTION_TIMEOUT, "Connection Timeout (ms)", composite); connectionTimeout.setPage(this); connectionTimeout.setPreferenceStore(getPreferenceStore()); connectionTimeout.load(); connectionTimeout.fillIntoGrid(composite, 3); socketTimeout = new IntegerFieldEditor( PreferenceConstants.P_SOCKET_TIMEOUT, "Socket Timeout (ms)", composite); socketTimeout.setPage(this); socketTimeout.setPreferenceStore(getPreferenceStore()); socketTimeout.load(); socketTimeout.fillIntoGrid(composite, 3); Link networkConnectionLink = new Link(composite, SWT.NULL); networkConnectionLink.setText( "See <a href=\"org.eclipse.ui.net.NetPreferences\">Network " + "connections</a> for more ways to configure how the AWS " + "Toolkit connects to the Internet."); PreferenceLinkListener preferenceLinkListener = new PreferenceLinkListener(); networkConnectionLink.addListener(SWT.Selection, preferenceLinkListener); return group; } /** * Insert links to the Java dev forum and aws-eclipse-feedback@amazon.com */ private void createFeedbackSection(final Composite composite) { WebLinkListener webLinkListener = new WebLinkListener(); String javaForumLinkText = "Get help or provide feedback on the " + Toolkit.createAnchor("AWS Java Development Forum", AwsUrls.JAVA_DEVELOPMENT_FORUM_URL); AwsToolkitPreferencePage.newLink(webLinkListener, javaForumLinkText, composite); EmailLinkListener feedbackLinkListener = new EmailLinkListener(EmailMessageLauncher.createEmptyFeedbackEmail()); String feedbackLinkText = "Or directly contact us via " + Toolkit.createAnchor(EmailMessageLauncher.AWS_ECLIPSE_FEEDBACK_AT_AMZN, EmailMessageLauncher.AWS_ECLIPSE_FEEDBACK_AT_AMZN); AwsToolkitPreferencePage.newLink(feedbackLinkListener, feedbackLinkText, composite); } /** * Save all the AccountInfo objects, and delete those that are to be * deleted. */ private void saveAccounts() { // Save all the AccountInfo objects // Because of data-binding, all the edits are already reflected inside // these AccountInfo objects for (AccountInfo account : accountInfoByIdentifier.values()) { account.save(); // Save the in-memory changes to the external source } // Remove the deleted accounts for (AccountInfo deletedAccount : accountInfoToBeDeleted) { deletedAccount.delete(); } accountInfoToBeDeleted.clear(); } private static class RegionSelectionDialog extends MessageDialog { private Region selectedRegion; private Font italicFont; protected RegionSelectionDialog() { super(Display.getDefault().getActiveShell(), "Select a region", AwsToolkitCore.getDefault() .getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON), "Configure the default AWS account for a specific region:" , MessageDialog.NONE, new String[] { "Cancel", "OK" }, 1); } @Override protected Control createCustomArea(final Composite parent) { final Combo regionSelector = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY); regionSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); for (Region region : RegionUtils.getRegions()) { regionSelector.add(region.getName()); regionSelector.setData(region.getName(), region); } final Label regionAccountExplanationLabel = new Label(parent, SWT.WRAP); FontData[] fontData = regionAccountExplanationLabel.getFont().getFontData(); for (FontData fd : fontData) { fd.setStyle(SWT.ITALIC); } italicFont = new Font(Display.getDefault(), fontData); regionAccountExplanationLabel.setFont(italicFont); regionSelector.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateSelectedRegion(regionSelector); } }); regionSelector.select(0); updateSelectedRegion(regionSelector); return regionSelector; } private void updateSelectedRegion(final Combo regionSelector) { String regionName = regionSelector.getItem(regionSelector.getSelectionIndex()); selectedRegion = (Region) regionSelector.getData(regionName); } @Override public boolean close() { if (italicFont != null) { italicFont.dispose(); } return super.close(); } public Region getSelectedRegion() { return selectedRegion; } } }
7,582
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences/ObfuscatingStringFieldEditor.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.preferences; import org.apache.commons.codec.binary.Base64; import org.eclipse.jface.preference.StringFieldEditor; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; /** * Extension of StringFieldEditor that obfuscates its data. */ public class ObfuscatingStringFieldEditor extends StringFieldEditor { /** * Creates a new ObfuscatingStringFieldEditor. * * @param preferenceKey * The name of the preference key. * @param labelText * The field editor's label text. * @param parent * The parent for this field editor. */ public ObfuscatingStringFieldEditor(String preferenceKey, String labelText, Composite parent) { super(preferenceKey, labelText, parent); } /* (non-Javadoc) * @see org.eclipse.jface.preference.StringFieldEditor#doLoad() */ @Override protected void doLoad() { Text textField = getTextControl(); if (textField == null) return; String value = getPreferenceStore().getString(getPreferenceName()); if (value == null) return; if (isBase64(value)) value = decodeString(value); textField.setText(value); } /* (non-Javadoc) * @see org.eclipse.jface.preference.StringFieldEditor#doStore() */ @Override protected void doStore() { Text textField = getTextControl(); if (textField == null) return; String encodedValue = encodeString(textField.getText()); getPreferenceStore().setValue(getPreferenceName(), encodedValue); } public static boolean isBase64(String s) { return Base64.isArrayByteBase64(s.getBytes()); } public static String encodeString(String s) { return new String(Base64.encodeBase64(s.getBytes())); } public static String decodeString(String s) { return new String(Base64.decodeBase64(s.getBytes())); } }
7,583
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences/AwsAccountPreferencePageTab.java
/* * Copyright 2008-2014 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.preferences; import java.io.File; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.UUID; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.BooleanFieldEditor; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; 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.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.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.events.ExpansionEvent; import org.eclipse.ui.forms.events.IExpansionListener; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.Section; import com.amazonaws.eclipse.core.AccountInfo; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.AwsUrls; import com.amazonaws.eclipse.core.accounts.AccountInfoImpl; import com.amazonaws.eclipse.core.accounts.preferences.PluginPreferenceStoreAccountOptionalConfiguration; import com.amazonaws.eclipse.core.accounts.profiles.SdkProfilesCredentialsConfiguration; import com.amazonaws.eclipse.core.accounts.profiles.SdkProfilesFactory; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.eclipse.core.ui.preferences.accounts.AccountInfoPropertyEditor; import com.amazonaws.eclipse.core.ui.preferences.accounts.AccountInfoPropertyEditorFactory; import com.amazonaws.eclipse.core.ui.preferences.accounts.AccountInfoPropertyEditorFactory.AccountInfoFilePropertyEditor; import com.amazonaws.eclipse.core.ui.preferences.accounts.AccountInfoPropertyEditorFactory.AccountInfoStringPropertyEditor; import com.amazonaws.eclipse.core.ui.preferences.accounts.AccountInfoPropertyEditorFactory.PropertyType; /** * A tab item contained in the AWS account preference page. Each tab item * corresponds to a set of region-specific (or global) accounts. */ public class AwsAccountPreferencePageTab extends TabItem { /** The preference store persisted by this tab */ private final IPreferenceStore prefStore; /** * The preference page to which the validation error message should be * reported. */ private final AwsAccountPreferencePage parentPrefPage; /** * The region associated with this tab. Null if this is the tab for global * account */ private final Region region; /** * The identifier of the current default account for the region represented * by this tab */ private String currentRegionAccountId; /** * @see AwsAccountPreferencePage#getAccountInfoByIdentifier() */ private final LinkedHashMap<String, AccountInfo> accountInfoByIdentifier; /** * @see AwsAccountPreferencePage#getAccountInfoToBeDeleted() */ private final Set<AccountInfo> accountInfoToBeDeleted; /** * The DataBindingContext instance shared by all the account info property * editors */ private final DataBindingContext dataBindingContext = new DataBindingContext(); /** * Additional listeners to be notified when the account information is modified */ private final List<ModifyListener> accountInfoFieldEditorListeners = new LinkedList<>(); /** Page controls */ BooleanFieldEditor enableRegionDefaultAccount; private Composite accountInfoSection; private ComboViewer accountSelector; private Button deleteAccount; private Label defaultAccountExplanationLabel; private AccountInfoPropertyEditor accountNameFieldEditor; private AccountInfoPropertyEditor accessKeyFieldEditor; private AccountInfoPropertyEditor secretKeyFieldEditor; private AccountInfoPropertyEditor sessionTokenFieldEditor; private AccountInfoPropertyEditor userIdFieldEditor; private AccountInfoPropertyEditor certificateFieldEditor; private AccountInfoPropertyEditor certificatePrivateKeyFieldEditor; /** * The set of field editors that need to know when the account or its name * changes. */ private final Collection<AccountInfoPropertyEditor> accountFieldEditors = new LinkedList<>(); /** The checkbox controlling how we display the secret key */ private Button hideSecretKeyCheckbox; /** The checkbox controlling whether the credential includes the session token */ private Button useSessionTokenCheckbox; /** The Text control in the secret key field editor */ private Text secretKeyText; public AwsAccountPreferencePageTab(TabFolder tabFolder, int tabIndex, AwsAccountPreferencePage parentPrefPage, Region region) { this(tabFolder, tabIndex, parentPrefPage, region, AwsToolkitCore .getDefault().getPreferenceStore()); } /** * Construct a new tab in the given TabFolder at the given index, relating * to the given region. * * @param tabFolder * TabFolder where this tab is inserted. * @param tabIndex * The index where this tab should be inserted. * @param parentPrefPage * The parent account preference page which contains this tab. * @param region * The region which this page tab manages * @param prefStore * The preference store that this tab persists with. */ public AwsAccountPreferencePageTab(TabFolder tabFolder, int tabIndex, AwsAccountPreferencePage parentPrefPage, Region region, IPreferenceStore prefStore) { super(tabFolder, SWT.NONE, tabIndex); this.parentPrefPage = parentPrefPage; this.accountInfoByIdentifier = parentPrefPage.getAccountInfoByIdentifier(); this.accountInfoToBeDeleted = parentPrefPage.getAccountInfoToBeDeleted(); this.region = region; this.prefStore = prefStore; if (region == null) { setText("Global Configuration"); } else { // Use the region name as the tab title setText(region.getName()); } loadCurrentDefaultAccountId(); writeDefaultPreferenceValues(); final Composite composite = setUpCompositeLayout(); // Not strictly necessary, since AwsAccountPreferencePage will never // construct this class with an empty map of accounts. if (!accountInfoByIdentifier.isEmpty()) { addControls(composite); } else { addCredentialsFileLoadingFailureLabel(composite); } setControl(composite); } /* * Public interfaces */ public void loadDefault() { if (enableRegionDefaultAccount != null) { enableRegionDefaultAccount.loadDefault(); } } public void doStore() { // Store the check box on whether region-default-account is enabled if (enableRegionDefaultAccount != null) { enableRegionDefaultAccount.store(); } // Save the id of the current default region account getPreferenceStore().setValue(getRegionCurrentAccountPrefKey(), currentRegionAccountId); // Refresh the UI of the account selector refreshAccountSelectorUI(); } public Region getRegion() { return region; } public boolean isGlobalAccoutTab() { return region == null; } /** * Returns names of all the accounts. */ public List<String> getAccountNames() { List<String> accountNames = new LinkedList<>(); for (AccountInfo account : accountInfoByIdentifier.values()) { accountNames.add(account.getAccountName()); } return accountNames; } /** * Check for duplicate account names in this tab. * * @return True if duplicate account names are found in this tab. */ public boolean checkDuplicateAccountName() { Set<String> accountNames = new HashSet<>(); for (String accountName : getAccountNames()) { if (!accountNames.add(accountName)) { return true; } } return false; } synchronized void addAccountInfoFieldEditorModifyListener(ModifyListener listener) { accountInfoFieldEditorListeners.add(listener); } /* * Private Interface */ private void loadCurrentDefaultAccountId() { currentRegionAccountId = getPreferenceStore().getString( getRegionCurrentAccountPrefKey()); } private void writeDefaultPreferenceValues() { if (!isGlobalAccoutTab()) { getPreferenceStore().setDefault(getRegionAccountEnabledPrefKey(), true); } } private Composite setUpCompositeLayout() { Composite composite = new Composite(getParent(), SWT.NONE); composite.setLayout(new GridLayout(3, false)); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); composite.setLayoutData(gridData); return composite; } private void addCredentialsFileLoadingFailureLabel(Composite composite) { new Label(composite, SWT.READ_ONLY) .setText(String .format("Failed to load credential profiles from (%s).%n" + "Please check that your credentials file is in the correct format.", prefStore .getString(PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION))); } private void addControls(final Composite composite) { // If it's regional tab, add the enable-region-default-account check-box // and the remove-this-tab button if (!isGlobalAccoutTab()) { addEnableRegionDefaultControls(composite); } // The main account info section accountInfoSection = createAccountInfoSection(composite); // Set up the change listener on the enable-region-default-account // check-box, so that the account info section is grayed out whenever // it's unchecked. setUpEnableRegionDefaultChangeListener(); AwsToolkitPreferencePage .tweakLayout((GridLayout) composite.getLayout()); } /** * Add the enable-region-default-account check-box and the remove-this-tab * button */ private void addEnableRegionDefaultControls(Composite parent) { enableRegionDefaultAccount = new BooleanFieldEditor( getRegionAccountEnabledPrefKey(), "Enable region default account for " + region.getName(), parent); enableRegionDefaultAccount.setPreferenceStore(getPreferenceStore()); Button removeTabButton = new Button(parent, SWT.PUSH); removeTabButton.setText("Remove"); removeTabButton .setToolTipText("Remove default account configuration for this region."); removeTabButton.setImage(AwsToolkitCore.getDefault().getImageRegistry() .get(AwsToolkitCore.IMAGE_REMOVE)); removeTabButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); removeTabButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { MessageDialog confirmRemoveTabDialog = new MessageDialog( Display.getDefault().getActiveShell(), "Remove all accounts for " + region.getName(), AwsToolkitCore.getDefault().getImageRegistry() .get(AwsToolkitCore.IMAGE_AWS_ICON), "Are you sure you want to remove all the configured accounts for " + region.getName() + "?", MessageDialog.CONFIRM, new String[] { "Cancel", "OK" }, 1); if (confirmRemoveTabDialog.open() == 1) { AwsAccountPreferencePageTab.this.dispose(); } } }); } /** * Creates the whole section of account info */ private Composite createAccountInfoSection(Composite parent) { Composite accountInfoSection = new Composite(parent, SWT.NONE); accountInfoSection.setLayout(new GridLayout()); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 3; accountInfoSection.setLayoutData(gridData); createAccountSelector(accountInfoSection); WebLinkListener webLinkListener = new WebLinkListener(); Group awsGroup = createAccountDetailSectionGroup(accountInfoSection, webLinkListener); createOptionalSection(awsGroup, webLinkListener); return accountInfoSection; } /** * Creates the account selection section. */ private Composite createAccountSelector(final Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); composite.setLayout(new GridLayout(4, false)); new Label(composite, SWT.READ_ONLY).setText("Default Profile: "); accountSelector = new ComboViewer(composite, SWT.DROP_DOWN | SWT.READ_ONLY); accountSelector.getCombo().setLayoutData( new GridData(SWT.FILL, SWT.CENTER, true, false)); // Use a List of AccountInfo objects as the data input for the combo // viewer accountSelector.setContentProvider(ArrayContentProvider.getInstance()); accountSelector.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { if (element instanceof AccountInfo) { AccountInfo account = (AccountInfo) element; if (account.isDirty()) { return "*" + account.getAccountName(); } else { return account.getAccountName(); } } return super.getText(element); } }); AccountInfo currentRegionAccount = accountInfoByIdentifier .get(currentRegionAccountId); // In some of the edge-cases, currentRegionAccount could be null. // e.g. a specific credential profile account is removed externally, but // the data in the preference store is not yet updated. if (currentRegionAccount == null) { currentRegionAccount = accountInfoByIdentifier.values().iterator() .next(); currentRegionAccountId = currentRegionAccount .getInternalAccountId(); } final List<AccountInfo> allAccounts = new LinkedList<>( accountInfoByIdentifier.values()); setUpAccountSelectorItems(allAccounts, currentRegionAccount); // Add selection listener to the account selector, so that all the // account info editors are notified of the newly selected AccountInfo // object. accountSelector .addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event .getSelection(); Object selectedObject = selection.getFirstElement(); if (selectedObject instanceof AccountInfo) { AccountInfo accountInfo = (AccountInfo) selectedObject; accountChanged(accountInfo); } } }); final Button addNewAccount = new Button(composite, SWT.PUSH); addNewAccount.setText("Add profile"); deleteAccount = new Button(composite, SWT.PUSH); deleteAccount.setText("Remove profile"); deleteAccount.setEnabled(allAccounts.size() > 1); defaultAccountExplanationLabel = new Label(composite, SWT.WRAP); defaultAccountExplanationLabel .setText(getDefaultAccountExplanationText()); parentPrefPage.setItalicFont(defaultAccountExplanationLabel); GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false); layoutData.horizontalSpan = 4; layoutData.widthHint = 200; defaultAccountExplanationLabel.setLayoutData(layoutData); addNewAccount.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String newAccountId = UUID.randomUUID().toString(); AccountInfo newAccountInfo = createNewProfileAccountInfo(newAccountId); String newAccountName = region == null ? "New Profile" : "New " + region.getName() + " Profile"; newAccountInfo.setAccountName(newAccountName); // this will mark the AccountInfo object dirty accountInfoByIdentifier.put(newAccountId, newAccountInfo); setUpAccountSelectorItems(accountInfoByIdentifier.values(), newAccountInfo); for (AwsAccountPreferencePageTab tab : parentPrefPage.getAllAccountPreferencePageTabs()) { if (tab != AwsAccountPreferencePageTab.this) { tab.refreshAccountSelectorItems(); } } parentPrefPage.updatePageValidationOfAllTabs(); } }); deleteAccount.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { accountInfoToBeDeleted.add(accountInfoByIdentifier .get(currentRegionAccountId)); accountInfoByIdentifier.remove(currentRegionAccountId); // If all the accounts are deleted, create a temporary // AccountInfo object if (accountInfoByIdentifier.isEmpty()) { String newAccountId = UUID.randomUUID().toString(); AccountInfo newAccountInfo = createNewProfileAccountInfo(newAccountId); // Account name : default-region-id newAccountInfo .setAccountName(getRegionAccountDefaultName()); accountInfoByIdentifier.put(newAccountId, newAccountInfo); } // Use the first AccountInfo as the next selected account AccountInfo nextDefaultAccount = accountInfoByIdentifier .values().iterator().next(); setUpAccountSelectorItems(accountInfoByIdentifier.values(), nextDefaultAccount); for (AwsAccountPreferencePageTab tab : parentPrefPage.getAllAccountPreferencePageTabs()) { if (tab != AwsAccountPreferencePageTab.this) { tab.refreshAccountSelectorItems(); } } parentPrefPage.updatePageValidationOfAllTabs(); } }); accountSelector.getCombo().addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent arg0) { if (accountSelector.getCombo().getItemCount() > 1) { deleteAccount.setEnabled(true); } else { deleteAccount.setEnabled(false); } } }); return composite; } /** * Refreshes the UI of the account selector. */ private void refreshAccountSelectorUI() { accountSelector.refresh(); } /** * Refreshes the input data for the account selector combo and keep the current * selection. */ private void refreshAccountSelectorItems() { setUpAccountSelectorItems(accountInfoByIdentifier.values(), accountInfoByIdentifier.get(currentRegionAccountId)); } /** * Set the input data for the account selector combo and also set the * selection to the specified AccountInfo object. */ private void setUpAccountSelectorItems(Collection<AccountInfo> allAccounts, AccountInfo selectedAccount) { accountSelector.setInput(allAccounts); // If the given account is not found, then select the first element if ( !allAccounts.contains(selectedAccount) ) { selectedAccount = allAccounts.iterator().next(); } accountSelector.setSelection(new StructuredSelection(selectedAccount), true); // visible=true // TODO: copied from the existing code, not sure why it's necessary accountSelector.getCombo().getParent().getParent().layout(); } /** * Creates the widgets for the AWS account information section on this * preference page. * * @param parent * The parent preference page composite. * @param webLinkListener * The listener to attach to links. */ private Group createAccountDetailSectionGroup(final Composite parent, WebLinkListener webLinkListener) { final Group awsAccountGroup = new Group(parent, SWT.NONE); GridData gridData1 = new GridData(SWT.FILL, SWT.TOP, true, false); gridData1.horizontalSpan = 4; gridData1.verticalIndent = 10; awsAccountGroup.setLayoutData(gridData1); awsAccountGroup.setText("Profile Details:"); if (isGlobalAccoutTab()) { String linkText = "<a href=\"" + AwsUrls.SIGN_UP_URL + "\">Sign up for a new AWS account</a> or " + "<a href=\"" + AwsUrls.SECURITY_CREDENTIALS_URL + "\">manage your existing AWS security credentials</a>."; AwsToolkitPreferencePage.newLink(webLinkListener, linkText, awsAccountGroup); AwsToolkitPreferencePage.createSpacer(awsAccountGroup); } accountNameFieldEditor = newStringFieldEditor( accountInfoByIdentifier.get(currentRegionAccountId), "accountName", "&Profile Name:", awsAccountGroup); accessKeyFieldEditor = newStringFieldEditor( accountInfoByIdentifier.get(currentRegionAccountId), "accessKey", "&Access Key ID:", awsAccountGroup); /* * Secret key editor and hide check-box */ secretKeyFieldEditor = newStringFieldEditor( accountInfoByIdentifier.get(currentRegionAccountId), "secretKey", "&Secret Access Key:", awsAccountGroup); // create an empty label in the first column so that the hide secret key // checkbox lines up with the other text controls new Label(awsAccountGroup, SWT.NONE); hideSecretKeyCheckbox = createCheckbox(awsAccountGroup, "Show secret access key", false); hideSecretKeyCheckbox.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { updateSecretKeyText(); } }); secretKeyText = secretKeyFieldEditor.getTextControl(); updateSecretKeyText(); /* * Session token input controls */ sessionTokenFieldEditor = newStringFieldEditor( accountInfoByIdentifier.get(currentRegionAccountId), "sessionToken", "Session &Token:", awsAccountGroup); new Label(awsAccountGroup, SWT.NONE); useSessionTokenCheckbox = createCheckbox(awsAccountGroup, "Use session token", false); useSessionTokenCheckbox.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { boolean useSessionToken = useSessionTokenCheckbox.getSelection(); AccountInfo currentAccount = accountInfoByIdentifier.get(currentRegionAccountId); currentAccount.setUseSessionToken(useSessionToken); updateSessionTokenControls(); parentPrefPage.updatePageValidationOfAllTabs(); } }); // Update session token controls according to the current account updateSessionTokenControls(); AwsToolkitPreferencePage.tweakLayout((GridLayout) awsAccountGroup .getLayout()); accountFieldEditors.add(accountNameFieldEditor); accountFieldEditors.add(accessKeyFieldEditor); accountFieldEditors.add(secretKeyFieldEditor); accountFieldEditors.add(sessionTokenFieldEditor); return awsAccountGroup; } private Button createCheckbox(Composite parent, String text, boolean defaultSelection) { Button checkbox = new Button(parent, SWT.CHECK); checkbox.setText(text); checkbox.setSelection(defaultSelection); GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = 2; gridData.verticalIndent = -6; gridData.horizontalIndent = 3; checkbox.setLayoutData(gridData); return checkbox; } /** * Creates the widgets for the optional configuration section on this * preference page. * * @param parent * The parent preference page composite. * @param webLinkListener * The listener to attach to links. */ private void createOptionalSection(final Composite parent, WebLinkListener webLinkListener) { Section expandableComposite = new Section(parent, ExpandableComposite.TWISTIE); GridData gd = new GridData(SWT.FILL, SWT.TOP, true, false); gd.horizontalSpan = AwsToolkitPreferencePage.LAYOUT_COLUMN_WIDTH; expandableComposite.setLayoutData(gd); Composite optionalConfigGroup = new Composite(expandableComposite, SWT.NONE); optionalConfigGroup.setLayout(new GridLayout()); optionalConfigGroup.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); expandableComposite.setClient(optionalConfigGroup); expandableComposite.setText("Optional configuration:"); expandableComposite.setExpanded(false); expandableComposite.addExpansionListener(new IExpansionListener() { @Override public void expansionStateChanging(ExpansionEvent e) { } @Override public void expansionStateChanged(ExpansionEvent e) { parent.getParent().layout(); } }); String linkText = "Your AWS account number and X.509 certificate are only needed if you want to bundle EC2 instances from Eclipse. " + "<a href=\"" + AwsUrls.SECURITY_CREDENTIALS_URL + "\">Manage your AWS X.509 certificate</a>."; AwsToolkitPreferencePage.newLink(webLinkListener, linkText, optionalConfigGroup); AwsToolkitPreferencePage.createSpacer(optionalConfigGroup); userIdFieldEditor = newStringFieldEditor( accountInfoByIdentifier.get(currentRegionAccountId), "userId", "AWS Account &Number:", optionalConfigGroup); createFieldExampleLabel(optionalConfigGroup, "ex: 1111-2222-3333"); certificateFieldEditor = newFileFieldEditor( accountInfoByIdentifier.get(currentRegionAccountId), "ec2CertificateFile", "&Certificate File:", optionalConfigGroup); certificatePrivateKeyFieldEditor = newFileFieldEditor( accountInfoByIdentifier.get(currentRegionAccountId), "ec2PrivateKeyFile", "&Private Key File:", optionalConfigGroup); AwsToolkitPreferencePage.tweakLayout((GridLayout) optionalConfigGroup .getLayout()); accountFieldEditors.add(userIdFieldEditor); accountFieldEditors.add(certificateFieldEditor); accountFieldEditors.add(certificatePrivateKeyFieldEditor); } /** * Set up the change listener on the enable-region-default-account * check-box, so that the account info section is grayed out whenever it's * unchecked. */ private void setUpEnableRegionDefaultChangeListener() { if (enableRegionDefaultAccount != null) { enableRegionDefaultAccount .setPropertyChangeListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { boolean enabled = (Boolean) event.getNewValue(); AwsAccountPreferencePageTab.this .toggleAccountInfoSectionEnabled(enabled); } }); enableRegionDefaultAccount.load(); toggleAccountInfoSectionEnabled(enableRegionDefaultAccount .getBooleanValue()); } } /** * Creates a new label to serve as an example for a field, using the * specified text. The label will be displayed with a subtle font. This * method assumes that the grid layout for the specified composite contains * three columns. * * @param composite * The parent component for this new widget. * @param text * The example text to display in the new label. */ private void createFieldExampleLabel(Composite composite, String text) { Label label = new Label(composite, SWT.NONE); Font font = label.getFont(); label = new Label(composite, SWT.NONE); label.setText(text); FontData[] fontData = font.getFontData(); if (fontData.length > 0) { FontData fd = fontData[0]; fd.setHeight(10); fd.setStyle(SWT.ITALIC); label.setFont(new Font(Display.getCurrent(), fd)); } GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = 2; gridData.verticalAlignment = SWT.TOP; gridData.horizontalIndent = 3; gridData.verticalIndent = -4; label.setLayoutData(gridData); } /** * Invoked whenever the selected account information changes. */ private void accountChanged(AccountInfo accountInfo) { currentRegionAccountId = accountInfo.getInternalAccountId(); for (AccountInfoPropertyEditor editor : accountFieldEditors) { editor.accountChanged(accountInfo); } updateSessionTokenControls(); } private void updateSessionTokenControls() { AccountInfo accountInfo = accountInfoByIdentifier.get(currentRegionAccountId); useSessionTokenCheckbox.setSelection(accountInfo.isUseSessionToken()); sessionTokenFieldEditor.getTextControl().setEnabled(accountInfo.isUseSessionToken()); } /** * Update or clear the error message and validity of the page. * * @return True if the page is invalid. */ boolean updatePageValidation() { String errorString = validateFieldValues(); if (errorString != null) { parentPrefPage.setValid(false); parentPrefPage.setErrorMessage(errorString); return true; } if (checkDuplicateAccountName()) { parentPrefPage.setValid(false); parentPrefPage.setErrorMessage("Duplicate account name defined"); return true; } return false; } /** * Returns an error message if there's a problem with the page's fields, or * null if there are no errors. */ private String validateFieldValues() { for (AccountInfo accountInfo : accountInfoByIdentifier.values()) { if (accountInfo.getAccountName().trim().isEmpty()) { return "Account name must not be blank"; } if (accountInfo.isUseSessionToken() && (accountInfo.getSessionToken() == null || accountInfo.getSessionToken().trim().isEmpty())) { return "Session token must not be blank"; } if (invalidFile(accountInfo.getEc2CertificateFile())) { return "Certificate file does not exist"; } if (invalidFile(accountInfo.getEc2PrivateKeyFile())) { return "Private key file does not exist"; } } return null; } private boolean invalidFile(String certFile) { return certFile.trim().length() > 0 && !new File(certFile).exists(); } /** * Updates the secret key text according to whether or not the * "display secret key in plain text" checkbox is selected or not. */ private void updateSecretKeyText() { if (hideSecretKeyCheckbox == null) return; if (secretKeyText == null) return; if (hideSecretKeyCheckbox.getSelection()) { secretKeyText.setEchoChar('\0'); } else { secretKeyText.setEchoChar('*'); } } private AccountInfoPropertyEditor newStringFieldEditor( AccountInfo currentAccount, String propertyName, String label, Composite parent) { AccountInfoPropertyEditor fieldEditor = AccountInfoPropertyEditorFactory .getAccountInfoPropertyEditor(currentAccount, propertyName, PropertyType.STRING_PROPERTY, label, parent, dataBindingContext); setUpFieldEditor(fieldEditor, parent); return fieldEditor; } private AccountInfoPropertyEditor newFileFieldEditor( AccountInfo currentAccount, String propertyName, String label, Composite parent) { AccountInfoPropertyEditor fieldEditor = AccountInfoPropertyEditorFactory .getAccountInfoPropertyEditor(currentAccount, propertyName, PropertyType.FILE_PROPERTY, label, parent, dataBindingContext); setUpFieldEditor(fieldEditor, parent); return fieldEditor; } protected void setUpFieldEditor( final AccountInfoPropertyEditor fieldEditor, Composite parent) { if (fieldEditor instanceof AccountInfoStringPropertyEditor) { ((AccountInfoStringPropertyEditor) fieldEditor) .getStringFieldEditor().fillIntoGrid(parent, AwsToolkitPreferencePage.LAYOUT_COLUMN_WIDTH); } else if (fieldEditor instanceof AccountInfoFilePropertyEditor) { ((AccountInfoFilePropertyEditor) fieldEditor).getFileFieldEditor() .fillIntoGrid(parent, AwsToolkitPreferencePage.LAYOUT_COLUMN_WIDTH); } // Validate the page whenever the editors are touched fieldEditor.getTextControl().addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { /* * Since the data-binding also observes the Modify event on the * text control, there is an edge case where the AccountInfo * model might not have been updated when the modifyText * callbacked is triggered. To make sure the updated data model * is visible to the subsequent operations, we forcefully push * the data from the editor to the data model. */ fieldEditor.forceUpdateEditorValueToAccountInfoModel(); /* * Now that the property value change has been applied to the * AccountInfo object. Since the accountSelector is backed by * the collection of the same AccountInfo objects, we can simply * refresh the UI of accountSelector; all the account name * changes will be reflected. */ for (AwsAccountPreferencePageTab tab : parentPrefPage.getAllAccountPreferencePageTabs()) { tab.refreshAccountSelectorUI(); } parentPrefPage.updatePageValidationOfAllTabs(); for (ModifyListener listener : accountInfoFieldEditorListeners) { listener.modifyText(null); } } }); } private String getRegionCurrentAccountPrefKey() { return PreferenceConstants.P_REGION_CURRENT_DEFAULT_ACCOUNT(region); } private String getRegionAccountDefaultName() { return PreferenceConstants.DEFAULT_ACCOUNT_NAME(region); } private String getRegionAccountEnabledPrefKey() { return PreferenceConstants.P_REGION_DEFAULT_ACCOUNT_ENABLED(region); } private IPreferenceStore getPreferenceStore() { return prefStore; } /** * Recursively enable/disable all the children controls of account-info * section. */ private void toggleAccountInfoSectionEnabled(boolean enabled) { AwsAccountPreferencePage.setEnabledOnAllChildern(accountInfoSection, enabled); } private AccountInfo createNewProfileAccountInfo(String newAccountId) { return new AccountInfoImpl(newAccountId, new SdkProfilesCredentialsConfiguration(prefStore, newAccountId, SdkProfilesFactory.newEmptyBasicProfile("")), new PluginPreferenceStoreAccountOptionalConfiguration( prefStore, newAccountId)); } private String getDefaultAccountExplanationText() { if (isGlobalAccoutTab()) { return "This credential profile will be used by default to access all AWS regions " + "that are not configured with a region-specific account."; } else { return "This credential profile will be used by default to access AWS resources in " + region.getName() + "(" + region.getId() + ") region."; } } /** * For debug purpose only. */ @SuppressWarnings("unused") private void printAccounts() { System.out.println("*** Default accounts(" + accountInfoByIdentifier.size() + ") tab for " + this.getText() + " ***"); for (String id : accountInfoByIdentifier.keySet()) { System.out.println(" " + accountInfoByIdentifier.get(id) + "(" + id + ")"); } System.out.println("Current default: " + accountInfoByIdentifier.get(currentRegionAccountId)); } /** * Override this method in order to let SWT allow sub-classing TabItem */ @Override public void checkSubclass() { // no-op } }
7,584
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences/AwsToolkitPreferencePage.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.preferences; import org.eclipse.jface.preference.FileFieldEditor; import org.eclipse.jface.preference.PreferencePage; 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.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Listener; /** * Abstract base class containing common logic for all AWS Toolkit preference * pages to share. */ public abstract class AwsToolkitPreferencePage extends PreferencePage { /** The layout column width for this page's field editors */ protected static final int LAYOUT_COLUMN_WIDTH = 3; /** * Constructs a new AwsToolkitPreferencePage. * * @param name * The title of this preference page. */ public AwsToolkitPreferencePage(String name) { super(name); } /** * Convenience method for creating a new Group with the specified label and * parent. * * @param groupText * The label for this new group. * @param parent * The parent for the new UI widget. * * @return The new Group widget. */ protected static Group newGroup(String groupText, Composite parent) { Group group = new Group(parent, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); group.setText(groupText); return group; } /** * Creates a new label with the specified text. * * @param labelText * The text for the label. * @param composite * The parent composite. * * @return The new Label. */ protected static Label newLabel(String labelText, Composite composite) { Label label = new Label(composite, SWT.WRAP); label.setText(labelText); GridData data = new GridData(SWT.FILL, SWT.FILL, false, false); data.horizontalSpan = LAYOUT_COLUMN_WIDTH; data.widthHint = 500; // SWT won't wrap without a widthHint label.setLayoutData(data); return label; } /** * Convenience method for creating a new Link widget. * * @param linkListener * The lister to add to the new Link. * @param linkText * The text for the new Link. * @param composite * The parent for the new Link. */ protected 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.FILL, false, false); data.horizontalSpan = LAYOUT_COLUMN_WIDTH; data.widthHint = 500; link.setLayoutData(data); return link; } /** * Creates a thin, empty composite to help space components vertically. * * @param parent * The composite this spacer is being added to. */ protected static void createSpacer(Composite parent) { Composite spacer = new Composite(parent, SWT.NONE); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.heightHint = 5; data.horizontalSpan = LAYOUT_COLUMN_WIDTH; spacer.setLayoutData(data); } /** * Tweaks the specified GridLayout to restore various settings. This method * is intended to be run after FieldEditors have been added to the parent * component so that anything they changed in the layout can be fixed. * * @param layout * The layout to tweak. */ protected static void tweakLayout(GridLayout layout) { layout.numColumns = LAYOUT_COLUMN_WIDTH; layout.marginWidth = 10; layout.marginHeight = 8; } /** * Creates a new ObfuscatingStringFieldEditor based on the specified * parameters. * * @param preferenceKey * The key for the preference managed by this field editor. * @param label * The label for this field editor. * @param parent * The parent for this field editor. * * @return The new FieldEditor. */ protected ObfuscatingStringFieldEditor newStringFieldEditor(String preferenceKey, String label, Composite parent) { ObfuscatingStringFieldEditor fieldEditor = new ObfuscatingStringFieldEditor(preferenceKey, label, parent); fieldEditor.setPage(this); fieldEditor.setPreferenceStore(this.getPreferenceStore()); fieldEditor.load(); fieldEditor.fillIntoGrid(parent, LAYOUT_COLUMN_WIDTH); return fieldEditor; } /** * Creates a new FileFieldEditor based on the specified parameters. * * @param preferenceKey * The key for the preference managed by this field editor. * @param label * The label for this field editor. * @param parent * The parent for this field editor. * * @return The new FieldEditor. */ protected FileFieldEditor newFileFieldEditor(String preferenceKey, String label, Composite parent) { FileFieldEditor fieldEditor = new FileFieldEditor(preferenceKey, label, parent); fieldEditor.setPage(this); fieldEditor.setPreferenceStore(this.getPreferenceStore()); fieldEditor.load(); fieldEditor.fillIntoGrid(parent, LAYOUT_COLUMN_WIDTH); return fieldEditor; } }
7,585
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences/accounts/LegacyPreferenceStoreAccountMerger.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.preferences.accounts; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; 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.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import com.amazonaws.eclipse.core.AccountInfo; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.accounts.AccountInfoImpl; import com.amazonaws.eclipse.core.accounts.AccountInfoProvider; import com.amazonaws.eclipse.core.accounts.preferences.PluginPreferenceStoreAccountOptionalConfiguration; import com.amazonaws.eclipse.core.accounts.profiles.SdkProfilesCredentialsConfiguration; import com.amazonaws.eclipse.core.accounts.profiles.SdkProfilesFactory; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.util.StringUtils; /** * A utility class responsible for merging the legacy account configurations * into the credentials file. */ public class LegacyPreferenceStoreAccountMerger { private static final IPreferenceStore prefStore = AwsToolkitCore.getDefault().getPreferenceStore(); private static boolean isEmpty(String s) { return (s == null || s.trim().length() == 0); } /** * NOTE: This method is safe to be invoked in non-UI thread. */ public static void mergeLegacyAccountsIntoCredentialsFile() { final AccountInfoProvider provider = AwsToolkitCore.getDefault() .getAccountManager().getAccountInfoProvider(); final Map<String, AccountInfo> legacyAccounts = provider.getAllLegacyPreferenceStoreAccontInfo(); // If there are no user created legacy accounts, then exit // early since there's nothing to merge. if (!hasValidLegacyAccounts(legacyAccounts)) { return; } final File credentialsFile = new File( prefStore .getString(PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION)); if ( !credentialsFile.exists() ) { /* * (1): The credentials file doesn't exist yet. * Silently write the legacy accounts into the credentials file */ saveAccountsIntoCredentialsFile(credentialsFile, legacyAccounts.values(), null); clearAllLegacyAccountsInPreferenceStore(); AwsToolkitCore.getDefault().logInfo(String.format( "%d legacy accounts added to the credentials file (%s).", legacyAccounts.size(), credentialsFile.getAbsolutePath())); } else { provider.refreshProfileAccountInfo(false, false); final Map<String, AccountInfo> profileAccounts = provider.getAllProfileAccountInfo(); if (profileAccounts.isEmpty()) { /* * (2) Failed to load from the existing credentials file. * Ask the user whether he/she wants to override the existing * file and dump the legacy accounts into it. */ Display.getDefault().asyncExec(new Runnable() { @Override public void run() { String MESSAGE = "The following legacy account configurations are detected in the system. " + "The AWS Toolkit now uses the credentials file to persist the credential configurations. " + "We cannot automatically merge the following accounts into your credentials file, " + "since the file already exists and is in invalid format. " + "Do you want to recreate the file using these account configurations?"; MergeLegacyAccountsConfirmationDialog dialog = new MergeLegacyAccountsConfirmationDialog( null, MESSAGE, new String[] { "Yes", "No" }, 0, legacyAccounts.values(), null, null); int result = dialog.open(); if (result == 0) { AwsToolkitCore.getDefault().logInfo("Deleting the credentials file before dumping the legacy accounts."); credentialsFile.delete(); saveAccountsIntoCredentialsFile(credentialsFile, legacyAccounts.values(), null); clearAllLegacyAccountsInPreferenceStore(); } } }); } else { /* * (3) Profile accounts successfully loaded. * Ask the user whether he/she wants to merge the legacy * accounts into the credentials file */ Display.getDefault().asyncExec(new Runnable() { @Override public void run() { String MESSAGE = "The following legacy account configurations are detected in the system. " + "The AWS Toolkit now uses the credentials file to persist the credential configurations. " + "Do you want to merge these accounts into your existing credentials file?"; Map<String, String> profileNameOverrides = checkDuplicateProfileName( legacyAccounts.values(), profileAccounts.values()); MergeLegacyAccountsConfirmationDialog dialog = new MergeLegacyAccountsConfirmationDialog( null, MESSAGE, new String[] { "Remove legacy accounts", "Yes", "No" }, 1, legacyAccounts.values(), profileAccounts.values(), profileNameOverrides); int result = dialog.open(); if (result == 1) { AwsToolkitCore.getDefault().logInfo("Coverting legacy accounts and merging them into the credentials file."); saveAccountsIntoCredentialsFile(credentialsFile, legacyAccounts.values(), profileNameOverrides); clearAllLegacyAccountsInPreferenceStore(); } else if (result == 0) { AwsToolkitCore.getDefault().logInfo("Removing legacy accounts"); clearAllLegacyAccountsInPreferenceStore(); } } }); } } } /** * @return True if customer has valid (the only accounts that are considered * invalid is the default generated empty account) legacy accounts, * false if not */ private static boolean hasValidLegacyAccounts( Map<String, AccountInfo> legacyAccounts) { if (legacyAccounts.isEmpty()) { return false; } else if (legacyAccounts.size() == 1) { AccountInfo accountInfo = legacyAccounts.values().iterator().next(); // A legacy default empty account is ignored if (accountInfo.getAccountName().equals(PreferenceConstants.DEFAULT_ACCOUNT_NAME) && isEmpty(accountInfo.getAccessKey()) && isEmpty(accountInfo.getSecretKey())) { return false; } } return true; } /** * Save the legacy preference-store-based accounts in the forms of * profile-based accounts. Note that we have to reuse the accountId, so that * the new profile accounts are still associated with the existing optional * configurations (userid, private key file, etc) stored in the preference * store. */ private static void saveAccountsIntoCredentialsFile(File destination, Collection<AccountInfo> legacyAccounts, Map<String, String> profileNameOverrides) { final List<String> legacyAccountIds = new LinkedList<>(); for (AccountInfo legacyAccount : legacyAccounts) { String legacyAccountName = legacyAccount.getAccountName(); String legacyAccountId = legacyAccount.getInternalAccountId(); legacyAccountIds.add(legacyAccountId); String newProfileName = legacyAccountName; if (profileNameOverrides != null && profileNameOverrides.get(legacyAccountName) != null) { newProfileName = profileNameOverrides.get(legacyAccountName); } // Construct a new profile-based AccountInfo object, reusing the accountId AccountInfo newProfileAccount = new AccountInfoImpl( legacyAccountId, new SdkProfilesCredentialsConfiguration( prefStore, legacyAccountId, SdkProfilesFactory.newEmptyBasicProfile("")), new PluginPreferenceStoreAccountOptionalConfiguration( prefStore, newProfileName)); // Explicitly use the setters so that the AccountInfo object will be marked as dirty newProfileAccount.setAccountName(newProfileName); newProfileAccount.setAccessKey(legacyAccount.getAccessKey()); newProfileAccount.setSecretKey(legacyAccount.getSecretKey()); newProfileAccount.setUserId(legacyAccount.getUserId()); newProfileAccount.setEc2PrivateKeyFile(legacyAccount.getEc2PrivateKeyFile()); newProfileAccount.setEc2CertificateFile(legacyAccount.getEc2CertificateFile()); newProfileAccount.save(); } // Then append the accountId to the "credentialProfileAccountIds" preference value String[] existingProfileAccountIds = prefStore.getString( PreferenceConstants.P_CREDENTIAL_PROFILE_ACCOUNT_IDS).split( PreferenceConstants.ACCOUNT_ID_SEPARATOR_REGEX); List<String> newProfileAccountIds = new LinkedList<>(Arrays.asList(existingProfileAccountIds)); newProfileAccountIds.addAll(legacyAccountIds); String newProfileAccountIdsString = StringUtils.join(PreferenceConstants.ACCOUNT_ID_SEPARATOR, newProfileAccountIds.toArray(new String[newProfileAccountIds.size()])); prefStore.setValue( PreferenceConstants.P_CREDENTIAL_PROFILE_ACCOUNT_IDS, newProfileAccountIdsString); } @SuppressWarnings("deprecation") private static void clearAllLegacyAccountsInPreferenceStore() { prefStore.setToDefault(PreferenceConstants.P_ACCOUNT_IDS); for (Region region : RegionUtils.getRegions()) { prefStore.setToDefault(PreferenceConstants.P_ACCOUNT_IDS(region)); } } /** * Checks duplicate names between the existing profile accounts and the * legacy accounts that are to be merged. * * @return A map from the duplicated legacy account name to the generated * new profile name. */ private static Map<String, String> checkDuplicateProfileName(Collection<AccountInfo> legacyAccounts, Collection<AccountInfo> existingProfileAccounts) { Set<String> exisitingProfileNames = new HashSet<>(); for (AccountInfo existingProfileAccount : existingProfileAccounts) { exisitingProfileNames.add(existingProfileAccount.getAccountName()); } Map<String, String> profileNameOverrides = new LinkedHashMap<>(); for (AccountInfo legacyAccount : legacyAccounts) { if (exisitingProfileNames.contains(legacyAccount.getAccountName())) { String newProfileName = generateNewProfileName(exisitingProfileNames, legacyAccount.getAccountName()); profileNameOverrides.put(legacyAccount.getAccountName(), newProfileName); } } return profileNameOverrides; } /** * Returns a new profile name that is not duplicate with the existing ones. */ private static String generateNewProfileName(Set<String> existingProfileNames, String profileName) { final String profileNameBase = profileName; int suffix = 1; while (existingProfileNames.contains(profileName)) { profileName = String.format("%s(%d)", profileNameBase, suffix++); } return profileName; } private static class MergeLegacyAccountsConfirmationDialog extends MessageDialog { private final Collection<AccountInfo> legacyAccounts; private final Collection<AccountInfo> existingProfileAccounts; private final Map<String, String> profileNameOverrides; private final boolean showExistingProfiles; public MergeLegacyAccountsConfirmationDialog( Shell parentShell, String message, String[] buttonLabels, int defaultButtonIndex, Collection<AccountInfo> legacyAccounts, Collection<AccountInfo> existingProfileAccounts, Map<String, String> profileNameOverrides) { super(parentShell, "Legacy Account Configurations", AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON), message, MessageDialog.QUESTION, buttonLabels, defaultButtonIndex); this.legacyAccounts = legacyAccounts; this.existingProfileAccounts = existingProfileAccounts; this.profileNameOverrides = profileNameOverrides; showExistingProfiles = existingProfileAccounts != null; } @Override protected Control createCustomArea(Composite parent) { final Composite composite = new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = showExistingProfiles ? 2 : 1; composite.setLayout(gridLayout); createLegacyAccountsTable(composite); if (showExistingProfiles) { createProfileAccountsTable(composite); } composite.setFocus(); return composite; } private void createLegacyAccountsTable(Composite parent) { final Table table = new Table(parent, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION); table.setLinesVisible(true); table.setHeaderVisible(true); GridData tableGridData = new GridData(SWT.CENTER, SWT.FILL, true, true); table.setLayoutData(tableGridData); TableColumn col = new TableColumn(table, SWT.NONE); col.setText("Legacy Accounts"); col.setWidth(75); for (AccountInfo legacyAccount : legacyAccounts) { TableItem item = new TableItem(table, SWT.NONE); item.setText(0, legacyAccount.getAccountName()); } col.pack(); } private void createProfileAccountsTable(Composite parent) { final Table table = new Table(parent, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION); table.setLinesVisible(true); table.setHeaderVisible(true); GridData tableGridData = new GridData(SWT.CENTER, SWT.FILL, true, true); table.setLayoutData(tableGridData); TableColumn col = new TableColumn(table, SWT.NONE); col.setText("Profile Accounts"); col.setWidth(75); for (AccountInfo existingProfileAccount : existingProfileAccounts) { TableItem item = new TableItem(table, SWT.NONE); item.setText(0, existingProfileAccount.getAccountName()); } for (AccountInfo legacyAccount : legacyAccounts) { TableItem item = new TableItem(table, SWT.NONE); String accountName = legacyAccount.getAccountName(); String text = profileNameOverrides == null || profileNameOverrides.get(accountName) == null ? accountName : profileNameOverrides.get(accountName); item.setText(0, text); item.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_RED)); } col.pack(); } } }
7,586
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences/accounts/AccountInfoPropertyEditor.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.preferences.accounts; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AccountInfo; /** * The abstract class that defines the basic behavior of a property editor for * an AccountInfo object. Subclasses are free to use any kind of UI widgets, as * long as it contains a SWT Text control that can be used for data-binding. */ public abstract class AccountInfoPropertyEditor { /** The AccountInfo object that is currently managed by this editor */ protected AccountInfo accountInfo; /** The name of the AccountInfo's POJO property that is managed by this editor */ protected final String propertyName; /** The DataBindingContext instance used for binding the AccountInfo object with the UI control */ private final DataBindingContext bindingContext; private Binding bindingWithCurrentAccountInfo; AccountInfoPropertyEditor(AccountInfo accountInfo, String propertyName, DataBindingContext bindingContext) { this.accountInfo = accountInfo; this.propertyName = propertyName; this.bindingContext = bindingContext; } /** * Update the accountInfo variable, and reset the databinding. */ public void accountChanged(AccountInfo newAccountInfo) { this.accountInfo = newAccountInfo; resetDataBinding(); } /** * Pro-actively push the text value of the editor to the underlying * AccountInfo model data. */ public void forceUpdateEditorValueToAccountInfoModel() { if (bindingWithCurrentAccountInfo != null) { bindingWithCurrentAccountInfo.updateTargetToModel(); } } /** * Implement this method to return the text control object used by the * editor. The returned text control object will be used as the target of * the data-binding. */ public abstract Text getTextControl(); /** * Reset the data-binding between the property of the AccountInfo POJO and * the text control provided by the concrete subclass. */ protected void resetDataBinding() { // Remove the current binding if (bindingWithCurrentAccountInfo != null) { bindingWithCurrentAccountInfo.dispose(); } IObservableValue modelValue = BeansObservables.observeValue( accountInfo, propertyName); IObservableValue viewValue = SWTObservables.observeText(getTextControl(), SWT.Modify); bindingWithCurrentAccountInfo = bindingContext.bindValue(viewValue, modelValue); } }
7,587
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/preferences/accounts/AccountInfoPropertyEditorFactory.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.preferences.accounts; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.jface.preference.FileFieldEditor; import org.eclipse.jface.preference.StringFieldEditor; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AccountInfo; /** * The factory class that returns AccountInfoPropertyEditor instances. */ public class AccountInfoPropertyEditorFactory { /** * Returns an AccountInfoPropertyEditor instance that binds to a specific * property of an AccountInfo object. * * @param accountInfo * The initial AccountInfo object * @param propertyName * The name of the property which is managed by this editor. * @param propertyType * The type of the property; either a String type or a File type. * @param bindingContext * The context for the data-binding with the AccountInfo model */ public static AccountInfoPropertyEditor getAccountInfoPropertyEditor(AccountInfo accountInfo, String propertyName, PropertyType propertyType, String labelText, Composite parent, DataBindingContext bindingContext) { if (propertyType == PropertyType.STRING_PROPERTY) { return new AccountInfoStringPropertyEditor(accountInfo, propertyName, labelText, parent, bindingContext); } else { return new AccountInfoFilePropertyEditor(accountInfo, propertyName, labelText, parent, bindingContext); } } /** * Different types of account info property which requires different UI * widgets as the editor. */ public enum PropertyType { STRING_PROPERTY, FILE_PROPERTY } /** * AccountInfoPropertyEditor implementation that uses JFace * StringFieldEditor as the UI widget. */ public static class AccountInfoStringPropertyEditor extends AccountInfoPropertyEditor { private final SimpleStringFieldEditor stringEditor; private final Composite parent; AccountInfoStringPropertyEditor(AccountInfo accountInfo, String propertyName, String labelText, Composite parent, DataBindingContext bindingContext) { super(accountInfo, propertyName, bindingContext); this.stringEditor = new SimpleStringFieldEditor(labelText, parent); this.parent = parent; resetDataBinding(); } @Override public Text getTextControl() { return stringEditor.getTextControl(parent); } /** * A package-private method returns the StringFieldEditor object. * AwsAccountPreferencePageTab class will use this method to call the * fillIntoGrid method. */ public StringFieldEditor getStringFieldEditor() { return stringEditor; } } /** * A subclass of StringFieldEditor that is not backed by any preference * store, and both store and load methods are overridden as no-op. */ private static class SimpleStringFieldEditor extends StringFieldEditor { public SimpleStringFieldEditor(String labelText, Composite parent) { super("", labelText, parent); } @Override public void store() { // no-op } @Override public void load() { // no-op } } /** * AccountInfoPropertyEditor implementation that uses JFace * FileFieldEditor as the UI widget. */ public static class AccountInfoFilePropertyEditor extends AccountInfoPropertyEditor { private final SimpleFileFieldEditor fileEditor; private final Composite parent; AccountInfoFilePropertyEditor(AccountInfo accountInfo, String propertyName, String labelText, Composite parent, DataBindingContext bindingContext) { super(accountInfo, propertyName, bindingContext); this.fileEditor = new SimpleFileFieldEditor(labelText, parent); this.parent = parent; resetDataBinding(); } @Override public Text getTextControl() { return fileEditor.getTextControl(parent); } /** * A package-private method returns the FileFieldEditor object. * AwsAccountPreferencePageTab class will use this method to call the * fillIntoGrid method. */ public FileFieldEditor getFileFieldEditor() { return fileEditor; } } /** * A subclass of StringFieldEditor that is not backed by any preference * store, and both store and load methods are overridden as no-op. */ private static class SimpleFileFieldEditor extends FileFieldEditor { public SimpleFileFieldEditor(String labelText, Composite parent) { super("", labelText, parent); } @Override public void store() {} @Override public void load() {} } }
7,588
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/menu/OpenWebConsoleHandler.java
/* * Copyright 2010-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.menu; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import com.amazonaws.eclipse.core.AwsUrls; import com.amazonaws.eclipse.core.BrowserUtils; public class OpenWebConsoleHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { BrowserUtils.openExternalBrowser(AwsUrls.AWS_MANAGEMENT_CONSOLE_URL); return null; } }
7,589
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/menu/OpenGeneralFeedbackEmailHandler.java
/* * Copyright 2010-2014 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.menu; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import com.amazonaws.eclipse.core.diagnostic.utils.EmailMessageLauncher; /** * Handler for the "com.amazonaws.eclipse.command.openGeneralFeedbackEmail" * (Report Bug or Enhancement) command. */ public class OpenGeneralFeedbackEmailHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { EmailMessageLauncher.createEmptyFeedbackEmail().open(); return null; } }
7,590
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/menu/OpenPreferencesHandler.java
/* * Copyright 2010-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.menu; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.ui.dialogs.PreferencesUtil; import com.amazonaws.eclipse.core.AwsToolkitCore; public class OpenPreferencesHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { String resource = AwsToolkitCore.ACCOUNT_PREFERENCE_PAGE_ID; PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn( null, resource, new String[] {resource}, null); return dialog.open(); } }
7,591
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/dialogs/CreateKmsKeyDialog.java
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui.dialogs; import java.util.Arrays; import org.eclipse.swt.widgets.Shell; import com.amazonaws.auth.policy.Policy; import com.amazonaws.auth.policy.Principal; import com.amazonaws.auth.policy.Resource; import com.amazonaws.auth.policy.Statement; import com.amazonaws.auth.policy.Statement.Effect; import com.amazonaws.auth.policy.actions.KMSActions; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase; import com.amazonaws.eclipse.core.model.SelectOrCreateKmsKeyDataModel.KmsKey; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.model.User; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.model.AliasListEntry; import com.amazonaws.services.kms.model.CreateAliasRequest; import com.amazonaws.services.kms.model.CreateKeyRequest; import com.amazonaws.services.kms.model.KeyListEntry; import com.amazonaws.services.kms.model.KeyMetadata; import com.amazonaws.services.kms.model.KeyUsageType; import com.amazonaws.services.kms.model.OriginType; public class CreateKmsKeyDialog extends AbstractInputDialog<KmsKey> { private final AwsResourceScopeParamBase param; private KmsKey kmsKey; public CreateKmsKeyDialog(Shell parentShell, AwsResourceScopeParamBase param) { super(parentShell, "Create KMS Key", "Create a KMS Key in " + RegionUtils.getRegion(param.getRegionId()).getName(), "Creating the KMS Key...", "KMS Key Alias Name:", "lambda-function-kms-key"); this.param = param; } @Override protected void performFinish(String input) { AWSKMS kmsClient = AwsToolkitCore.getClientFactory(param.getAccountId()) .getKmsClientByRegion(param.getRegionId()); AmazonIdentityManagement iamClient = AwsToolkitCore.getClientFactory(param.getAccountId()) .getIAMClientByRegion(param.getRegionId()); User iamUser = iamClient.getUser().getUser(); Policy policy = new Policy(); Statement statement = new Statement(Effect.Allow); statement.setPrincipals(new Principal(iamUser.getArn())); statement.setActions(Arrays.asList(KMSActions.AllKMSActions)); statement.setResources(Arrays.asList(new Resource("*"))); policy.setStatements(Arrays.asList(statement)); KeyMetadata keyMetadata = kmsClient.createKey(new CreateKeyRequest() .withKeyUsage(KeyUsageType.ENCRYPT_DECRYPT) .withOrigin(OriginType.AWS_KMS) .withPolicy(policy.toJson())) .getKeyMetadata(); input = KmsKey.KMS_KEY_ALIAS_PREFIX + input; kmsClient.createAlias(new CreateAliasRequest() .withAliasName(input) .withTargetKeyId(keyMetadata.getKeyId())); KeyListEntry key = new KeyListEntry() .withKeyId(keyMetadata.getKeyId()) .withKeyArn(keyMetadata.getArn()); AliasListEntry alias = new AliasListEntry() .withAliasName(input) .withTargetKeyId(keyMetadata.getKeyId()); kmsKey = new KmsKey(key, alias); } @Override public KmsKey getCreatedResource() { return kmsKey; } }
7,592
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/dialogs/AbstractInputDialog.java
package com.amazonaws.eclipse.core.ui.dialogs; /* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ProgressBar; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public abstract class AbstractInputDialog<T> extends TitleAreaDialog { private final String title; private final String message; private final String messageDuringAction; private final String inputFieldLabel; private final String defaultInputValue; private Text inputText; private ProgressBar progressBar; /** * We store it memory so that we still have access to the input if the text * field has been disposed. */ protected String inputValue; /** * Invoked after the user clicks OK button. Note this method is not called * in the main thread. So any UI update in this method should be guarded by * Display.syncExec or Display.asyncExec. */ protected abstract void performFinish(String input); /** * Return the newly created resource. */ public abstract T getCreatedResource(); protected AbstractInputDialog(Shell parentShell, String title, String message, String messageDuringAction, String inputFieldLabel, String defaultInputValue) { super(parentShell); this.title = title; this.message = message; this.messageDuringAction = messageDuringAction; this.inputFieldLabel = inputFieldLabel; this.defaultInputValue = defaultInputValue; inputValue = defaultInputValue; } @Override public void create() { super.create(); setTitle(title); setMessage(message, IMessageProvider.NONE); } @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout layout = new GridLayout(2, false); layout.marginTop = 20; layout.verticalSpacing = 40; container.setLayout(layout); Label label = new Label(container, SWT.NONE); label.setText(inputFieldLabel); inputText = new Text(container, SWT.BORDER); GridData gridData = new GridData(GridData.FILL_HORIZONTAL); inputText.setLayoutData(gridData); inputText.setText(defaultInputValue); inputText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent arg0) { inputValue = inputText.getText(); if (inputValue.isEmpty()) { getButton(IDialogConstants.OK_ID).setEnabled(false); } else { getButton(IDialogConstants.OK_ID).setEnabled(true); } } }); progressBar = new ProgressBar(container, SWT.INDETERMINATE); progressBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridData gd = new GridData(SWT.FILL, SWT.BOTTOM, true, false); gd.horizontalSpan = 2; progressBar.setLayoutData(gd); progressBar.setVisible(false); return container; } @Override protected void okPressed() { setErrorMessage(null); setMessage(messageDuringAction); getButton(IDialogConstants.OK_ID).setEnabled(false); getButton(IDialogConstants.CANCEL_ID).setEnabled(false); progressBar.setVisible(true); new Thread(new Runnable() { @Override public void run() { try { performFinish(AbstractInputDialog.this.inputValue); } catch (final Exception e) { // hide progress bar Display.getDefault().syncExec(new Runnable() { @Override public void run() { setErrorMessage(e.getMessage()); progressBar.setVisible(false); getButton(IDialogConstants.OK_ID).setEnabled(true); getButton(IDialogConstants.CANCEL_ID).setEnabled(true); } }); return; } Display.getDefault().syncExec(new Runnable() { @Override public void run() { AbstractInputDialog.super.okPressed(); } }); } }).start(); } }
7,593
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/dialogs/CreateS3BucketDialog.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.core.ui.dialogs; import org.eclipse.swt.widgets.Shell; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.CreateBucketRequest; public class CreateS3BucketDialog extends AbstractInputDialog<Bucket> { private final AwsResourceScopeParamBase param; private Bucket createdBucket; public CreateS3BucketDialog(Shell parentShell, AwsResourceScopeParamBase param) { super( parentShell, "Create Bucket", "Create an S3 bucket in " + RegionUtils.getRegion(param.getRegionId()) + " region", "Creating the Bucket...", "Bucket Name:", "lambda-function-bucket-" + param.getRegionId() + "-" + System.currentTimeMillis()); this.param = param; } public Bucket getCreatedBucket() { return getCreatedResource(); } @Override protected void performFinish(String input) { AmazonS3 s3 = AwsToolkitCore.getClientFactory(param.getAccountId()) .getS3ClientByRegion(param.getRegionId()); String regionId = param.getRegionId(); String s3RegionName = regionId.equalsIgnoreCase("us-east-1") ? null : regionId; createdBucket = s3.createBucket(new CreateBucketRequest(input, s3RegionName)); } @Override public Bucket getCreatedResource() { return createdBucket; } }
7,594
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/wizards/TwoPhaseValidator.java
/* * Copyright 2008-2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.wizards; import org.eclipse.core.databinding.observable.map.IObservableMap; import org.eclipse.core.databinding.observable.map.WritableMap; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.validation.MultiValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.widgets.Display; /** * An Eclipse MultiValidator that runs a two-phase validation process * using pluggable InputValidator strategies. First, an optional synchronous * validation phase is run to check for well-formed input. If this phase * passes, an optional asynchronous phase is run to eg make a call to a * remote service to check an existence constraint. * <p/> * Both phases are optional, although a TwoPhaseValidator with a no-op for * both phases is a particularly inefficient way of doing nothing. */ class TwoPhaseValidator extends MultiValidator { /** * How long to wait before actually running async validation, to cut * down on churn when the user is actively changing the input. */ private static final long ASYNC_DELAY_MILLIS = 200; private final IObservableValue observableInput; private final InputValidator syncValidator; private final InputValidator asyncValidator; /** * A cache of values we've previously validated asynchronously; if we * see these values again, we'll be lazy and simply report the cached * value rather than re-running (potentially-expensive) async validation. * <p/> * The cache is not size-bound, since it's <i>probably</i> not an issue * in practice, and WritableMap doesn't expose an easy way to expire * entries from the cache. * <p/> * Access is protected by a lock on the TwoPhaseValidator. */ private final IObservableMap asyncCache; /** * The currently-scheduled async validation job (or null if no job * is currently scheduled). We remember this so we can cancel the * job if the input changes before the job has actually started * running. * <p/> * Access is protected by a lock on the TwoPhaseValidator. */ private Job asyncValidationJob; /** * Constructor. * * @param observableInput the value to validate * @param syncValidator the optional synchronous validator * @param asyncValidator the optional asynchronous validator */ public TwoPhaseValidator( final IObservableValue observableInput, final InputValidator syncValidator, final InputValidator asyncValidator ) { this.observableInput = observableInput; this.syncValidator = syncValidator; this.asyncValidator = asyncValidator; if (asyncValidator == null) { asyncCache = null; } else { asyncCache = new WritableMap(); // Observe the cache; the background validation job will write // it's status to the cache. If the user hasn't changed the input // value since we started the async validation, we'll find the // result in the cache when revalidating and update the UI // as appropriate. super.observeValidatedMap(asyncCache); } } /** * Validate the current input value. * * @return an OK status if the value is valid, an error otherwise */ @Override protected IStatus validate() { Object input = observableInput.getValue(); if (syncValidator != null) { // Run synchronous validation synchronously IStatus rval = syncValidator.validate(input); if (!rval.isOK()) { return rval; } } if (asyncValidator == null) { // Nothing else to do, just report OK. return ValidationStatus.ok(); } synchronized (this) { // If there is a pending async validation job, cancel it; the // value has changed, so it is no longer relevant. if (asyncValidationJob != null) { asyncValidationJob.cancel(); asyncValidationJob = null; } // Check for a cached validation of the current value; if there // is one, we can go ahead and return that rather than kicking // off a background validation. IStatus cachedStatus = (IStatus) asyncCache.get(input); if (cachedStatus != null) { return cachedStatus; } // No cached validation status; schedule an async validation job // to run if the value stays stable for a little while. In the // meantime, report that we're still in the middle of validating. asyncValidationJob = new AsyncValidationJob(input); asyncValidationJob.schedule(ASYNC_DELAY_MILLIS); return ValidationStatus.error("Validating..."); } } /** * A background job that runs our asyncValidator with a given input * and calls back to the UI thread when it's finished to report whether * the input was valid or not */ private class AsyncValidationJob extends Job { private final Object input; /** * Constructor input the input to validate */ public AsyncValidationJob(final Object input) { super("AWS Toolkit Async Validation Job"); super.setPriority(Job.DECORATE); this.input = input; } /** * Run the async validator and call back to the UI thread with its * result. */ @Override protected IStatus run(final IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } final IStatus rval = asyncValidator.validate(input); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { synchronized (TwoPhaseValidator.this) { // If we haven't been canceled and replaced, // deregister us so we can be GC'd. if (asyncValidationJob == AsyncValidationJob.this) { asyncValidationJob = null; } // Drop the status into the cache. The // TwoPhaseValidator is watching the cache, and so // validation will re-run, picking up the cached // value this time. asyncCache.put(input, rval); } } }); return Status.OK_STATUS; } } }
7,595
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/wizards/CompositeWizardPage.java
/* * Copyright 2011-2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.wizards; import java.util.LinkedHashMap; import java.util.Map; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; /** * A generic wizard page which is driven by a set of WizardPageInputs, all of * which must have valid inputs for the page to be complete. */ public class CompositeWizardPage extends WizardPage { private final Map<String, WizardPageInput> inputs; /** * Construct a new CompositeWizardPage. * * @param pageName the name of the page (where does this show up?) * @param title the title of the page * @param titleImage image to show in the page title bar */ public CompositeWizardPage(final String pageName, final String title, final ImageDescriptor titleImage) { super(pageName, title, titleImage); this.inputs = new LinkedHashMap<>(); } /** * Add a named input to the page. Inputs have a name which can be used to * retrieve their values using getValue() once the page is complete. */ public void addInput(final String name, final WizardPageInput input) { if (name == null) { throw new IllegalArgumentException("name cannot be null"); } if (input == null) { throw new IllegalArgumentException("input cannot be null"); } if (inputs.containsKey(name)) { throw new IllegalArgumentException( "this page already has an input named " + name ); } inputs.put(name, input); } /** * Get the value entered for the given named input. * * @param inputName the name of the input to query * @return the value of the input */ public Object getInputValue(final String inputName) { WizardPageInput input = inputs.get(inputName); if (input == null) { throw new IllegalArgumentException("No input named " + inputName); } return input.getValue(); } /** * Create the control for the page. Creates a basic layout, then invokes * each previously-added input (in the order they were added) to add * itself to the grid. * * @param parent the parent composite to create this page within */ @Override public void createControl(final Composite parent) { GridLayout layout = new GridLayout(2, false); layout.horizontalSpacing = 10; Composite composite = new Composite(parent, SWT.None); composite.setLayout(layout); DataBindingContext context = new DataBindingContext(); for (Map.Entry<String, WizardPageInput> entry : inputs.entrySet()) { entry.getValue().init(composite, context); } bindValidationStatus(context); super.setControl(composite); } /** * Bind the most severe validation error from any validation status * providers added to the binding context by our inputs to the UI * for the page, displaying an error message and marking the page as * incomplete if one of the input values is invalid. * * @param context the data binding context for all inputs */ private void bindValidationStatus(final DataBindingContext context) { final AggregateValidationStatus status = new AggregateValidationStatus( context, AggregateValidationStatus.MAX_SEVERITY ); status.addChangeListener(new IChangeListener() { @Override public void handleChange(final ChangeEvent event) { updateValidationStatus((IStatus) status.getValue()); } }); updateValidationStatus((IStatus) status.getValue()); } /** * Update the message and completion flag for this page based on * the current validation status of the inputs. * * @param status the aggregated current validation status */ private void updateValidationStatus(final IStatus status) { super.setMessage(status.getMessage(), status.getSeverity()); super.setPageComplete(status.isOK()); } }
7,596
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/wizards/ErrorDecorator.java
/* * Copyright 2008-2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.wizards; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.IValueChangeListener; import org.eclipse.core.databinding.observable.value.ValueChangeEvent; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Control; /** * An IValueChangeListener that watches the validation status for a * particular control and adds an error decoration whenever validation * fails. */ public class ErrorDecorator implements IValueChangeListener { private final ControlDecoration decoration; /** * Create a new Error decorator. * * @param control the control to decorate */ public ErrorDecorator(final Control control) { decoration = new ControlDecoration(control, SWT.TOP | SWT.LEFT); decoration.setImage(FieldDecorationRegistry .getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR) .getImage() ); } /** * Create a new ErrorDecorator attached to the given control and * bind it to an IObservableValue tracking an IStatus indicating whether * the value in the control is valid. * * @param control the control to decorate * @param status the status to observe */ public static void bind(final Control control, final IObservableValue status) { ErrorDecorator decorator = new ErrorDecorator(control); status.addValueChangeListener(decorator); // Update the decoration with the current status value. decorator.update((IStatus) status.getValue()); } /** * React to a change in the validation status by updating the decoration. * * @param event the value change event */ @Override public void handleValueChange(final ValueChangeEvent event) { update((IStatus) event.getObservableValue().getValue()); } /** * Update the decoration based on the current validation status of the * control. If the input value is valid, hide the decoration. If not, * show the decoration and display the error text to the user. * * @param status the current validation status */ private void update(final IStatus status) { if (status.isOK()) { decoration.hide(); } else { decoration.setDescriptionText(status.getMessage()); decoration.show(); } } }
7,597
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/wizards/WizardPageInput.java
/* * Copyright 2008-2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.wizards; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.swt.widgets.Composite; /** * An input field of a CompositeWizardPage. Captures a single value from the * user. */ public interface WizardPageInput { /** * Initialize the input. * * @param parent the parent composite * @param context the data binding context for the page */ void init(Composite parent, DataBindingContext context); /** * @return the value the user added to this input */ Object getValue(); /** * Dispose any resources owned by this input. */ void dispose(); }
7,598
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/wizards/InputValidator.java
/* * Copyright 2008-2013 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.core.ui.wizards; import org.eclipse.core.runtime.IStatus; /** * A pluggable validation strategy. */ public interface InputValidator { /** * Validate whether the given value is valid (for some definition of * valid). Return an OK status if so; if not, return an error status * describing why it's not for display to the user. * * @param value the value to validate * @return the validation status */ IStatus validate(final Object value); }
7,599