index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/CreateTopicDialog.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sns;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* Dialog to create a new SNS topic.
*/
public class CreateTopicDialog extends MessageDialog {
private String topicName;
public CreateTopicDialog() {
super(Display.getDefault().getActiveShell(), "Create New SNS Topic", null, "Enter the name for your new SNS Topic.",
MessageDialog.INFORMATION, new String[] {"OK", "Cancel"}, 0);
}
public String getTopicName() {
return topicName;
}
@Override
protected Control createCustomArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
composite.setLayout(new GridLayout(2, false));
new Label(composite, SWT.NONE).setText("Topic Name:");
final Text topicNameText = new Text(composite, SWT.BORDER);
topicNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
topicNameText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
topicName = topicNameText.getText();
updateControls();
}
});
return composite;
}
private void updateControls() {
boolean isValid = (topicName != null && topicName.trim().length() > 0);
Button okButton = this.getButton(0);
if (okButton != null) okButton.setEnabled(isValid);
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
updateControls();
}
} | 7,800 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/CreateTopicWizard.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.explorer.sns;
import java.util.regex.Pattern;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.AmazonClientException;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.wizards.CompositeWizardPage;
import com.amazonaws.eclipse.core.ui.wizards.InputValidator;
import com.amazonaws.eclipse.core.ui.wizards.TextWizardPageInput;
import com.amazonaws.eclipse.core.ui.wizards.WizardPageInput;
import com.amazonaws.eclipse.explorer.ContentProviderRegistry;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.CreateTopicResult;
import com.amazonaws.services.sns.model.SetTopicAttributesRequest;
/**
* A wizard for creating an SNS topic.
*/
public class CreateTopicWizard extends Wizard {
private final CompositeWizardPage page;
/**
* Constructor.
*/
public CreateTopicWizard() {
page = new CompositeWizardPage(
"Create New SNS Topic",
"Create New SNS Topic",
AwsToolkitCore.getDefault()
.getImageRegistry()
.getDescriptor("aws-logo")
);
WizardPageInput topicName = new TextWizardPageInput(
"Topic Name: ",
null, // no descriptive text.
TopicNameValidator.INSTANCE,
null // no async validation possible for topic names.
);
WizardPageInput displayName = new TextWizardPageInput(
"Display Name: ",
"An optional display name for this topic.",
DisplayNameValidator.INSTANCE,
null // no async validation here either.
);
page.addInput(TOPIC_NAME_INPUT, topicName);
page.addInput(DISPLAY_NAME_INPUT, displayName);
}
@Override
public void addPages() {
super.addPage(page);
}
@Override
public int getPageCount() {
return 1;
}
@Override
public boolean needsPreviousAndNextButtons() {
return false;
}
@Override
public boolean performFinish() {
String topicName = (String) page.getInputValue(TOPIC_NAME_INPUT);
String displayName = (String) page.getInputValue(DISPLAY_NAME_INPUT);
AmazonSNS client = AwsToolkitCore.getClientFactory().getSNSClient();
CreateTopicResult result =
client.createTopic(new CreateTopicRequest(topicName));
if (displayName != null && displayName.length() > 0) {
try {
client.setTopicAttributes(new SetTopicAttributesRequest()
.withTopicArn(result.getTopicArn())
.withAttributeName(DISPLAY_NAME_ATTRIBUTE)
.withAttributeValue(displayName)
);
} catch (AmazonClientException exception) {
AwsToolkitCore.getDefault().logError(
"Error setting topic display name",
exception
);
MessageDialog dialog = new MessageDialog(
Display.getCurrent().getActiveShell(),
"Warning",
null,
("The topic was successfully created, but the display "
+ "name could not be set (" + exception.toString()
+ ")"),
MessageDialog.WARNING,
new String[] { "OK" },
0
);
dialog.open();
}
}
ContentProviderRegistry.refreshAllContentProviders();
return true;
}
private static final String TOPIC_NAME_INPUT = "topicName";
private static final String DISPLAY_NAME_INPUT = "displayName";
private static final String DISPLAY_NAME_ATTRIBUTE = "DisplayName";
/**
* Synchronous validator for topic names.
*/
private static class TopicNameValidator implements InputValidator {
public static TopicNameValidator INSTANCE = new TopicNameValidator();
/** {@inheritDoc} */
@Override
public IStatus validate(final Object value) {
String topicName = (String) value;
if (topicName == null || topicName.length() == 0) {
return ValidationStatus.error("Please enter a topic name");
}
if (topicName.length() > MAX_TOPIC_NAME_LENGTH) {
return ValidationStatus.error(String.format(
"Topic names may not exceed %d characters",
MAX_TOPIC_NAME_LENGTH
));
}
if (!TOPIC_NAME_PATTERN.matcher(topicName).matches()) {
return ValidationStatus.error(
"Topic names may only contain letters, numbers, '-', "
+ "or '_'"
);
}
return ValidationStatus.ok();
}
/**
* I'm stateless, use my singleton INSTANCE.
*/
private TopicNameValidator() {
}
/**
* Valid characters which can appear in a topic name, per
* http://aws.amazon.com/sns/faqs/#10.
*/
private static final Pattern TOPIC_NAME_PATTERN =
Pattern.compile("[A-Za-z0-9-_]+");
private static final int MAX_TOPIC_NAME_LENGTH = 256;
}
/**
* Synchronous validator for display names.
*/
private static class DisplayNameValidator implements InputValidator {
public static DisplayNameValidator INSTANCE =
new DisplayNameValidator();
/** {@inheritDoc} */
@Override
public IStatus validate(final Object value) {
String displayName = (String) value;
if (displayName == null || displayName.length() == 0) {
// Display name is optional.
return ValidationStatus.ok();
}
if (displayName.length() > MAX_DISPLAY_NAME_LENGTH) {
return ValidationStatus.error(String.format(
"Display names may not exceed %d characters",
MAX_DISPLAY_NAME_LENGTH
));
}
return ValidationStatus.ok();
}
private static final int MAX_DISPLAY_NAME_LENGTH = 100;
}
}
| 7,801 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/SNSContentProvider.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sns;
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;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.ListTopicsRequest;
import com.amazonaws.services.sns.model.ListTopicsResult;
import com.amazonaws.services.sns.model.Topic;
public class SNSContentProvider extends AbstractContentProvider {
/**
* Parse a topic name from a topic ARN, for friendlier display in
* the UI.
*
* @param topicARN the ARN of the topic
* @return the user-assigned name of the topic
*/
public static String parseTopicName(final String topicARN) {
int index = topicARN.lastIndexOf(':');
if (index > 0) {
return topicARN.substring(index + 1);
}
return topicARN;
}
public static class SNSRootElement {
public static final SNSRootElement ROOT_ELEMENT = new SNSRootElement();
}
public static class TopicNode extends ExplorerNode {
private final Topic topic;
public TopicNode(Topic topic) {
super(parseTopicName(topic.getTopicArn()),
0,
loadImage(AwsToolkitCore.IMAGE_TOPIC),
new OpenTopicEditorAction(topic));
this.topic = topic;
}
public Topic getTopic() {
return topic;
}
}
@Override
public boolean hasChildren(Object element) {
return (element instanceof AWSResourcesRootElement ||
element instanceof SNSRootElement);
}
@Override
public Object[] loadChildren(Object parentElement) {
if (parentElement instanceof AWSResourcesRootElement) {
return new Object[] { SNSRootElement.ROOT_ELEMENT };
}
if (parentElement instanceof SNSRootElement) {
new DataLoaderThread(parentElement) {
@Override
public Object[] loadData() {
AmazonSNS sns = AwsToolkitCore.getClientFactory().getSNSClient();
List<TopicNode> topicNodes = new ArrayList<>();
ListTopicsResult listTopicsResult = null;
do {
if (listTopicsResult == null) {
listTopicsResult = sns.listTopics();
} else {
listTopicsResult = sns.listTopics(
new ListTopicsRequest(listTopicsResult.getNextToken()));
}
for (Topic topic : listTopicsResult.getTopics()) {
topicNodes.add(new TopicNode(topic));
}
} while (listTopicsResult.getNextToken() != null);
return topicNodes.toArray();
}
}.start();
}
return Loading.LOADING;
}
@Override
public String getServiceAbbreviation() {
return ServiceAbbreviations.SNS;
}
}
| 7,802 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/SNSActionProvider.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sns;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.navigator.CommonActionProvider;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.ContentProviderRegistry;
import com.amazonaws.eclipse.explorer.sns.SNSContentProvider.TopicNode;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.DeleteTopicRequest;
import com.amazonaws.services.sns.model.Topic;
public class SNSActionProvider extends CommonActionProvider {
@Override
public void fillContextMenu(IMenuManager menu) {
StructuredSelection selection = (StructuredSelection)getActionSite().getStructuredViewer().getSelection();
menu.add(new CreateTopicAction());
boolean showDeleteMenuItem = true;
List<Topic> selectedTopics = new ArrayList<>();
Iterator iterator = selection.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
if (next instanceof TopicNode) {
selectedTopics.add(((TopicNode)next).getTopic());
} else {
showDeleteMenuItem = false;
}
}
if (selectedTopics.size() > 0 && showDeleteMenuItem) {
menu.add(new DeleteTopicAction(selectedTopics));
menu.add(new Separator());
}
if (selectedTopics.size() == 1) {
AmazonSNS sns = AwsToolkitCore.getClientFactory().getSNSClient();
menu.add(new PublishMessageAction(sns, selectedTopics.get(0)));
menu.add(new NewSubscriptionAction(sns, selectedTopics.get(0), null));
}
}
private Dialog newConfirmationDialog(String title, String message) {
return new MessageDialog(Display.getDefault().getActiveShell(), title, null, message, MessageDialog.WARNING, new String[] {"OK", "Cancel"}, 0);
}
public class DeleteTopicAction extends Action {
private final List<Topic> topics;
public DeleteTopicAction(List<Topic> topics) {
this.topics = topics;
this.setText("Delete Topic" + (topics.size() > 1 ? "s" : ""));
this.setToolTipText("Delete the selected Amazon SNS topics");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE));
}
@Override
public void run() {
Dialog dialog = newConfirmationDialog("Delete selected topics?", "Are you sure you want to delete the selected Amazon SNS topics?");
if (dialog.open() != 0) return;
AmazonSNS sns = AwsToolkitCore.getClientFactory().getSNSClient();
for (Topic topic : topics) {
try {
sns.deleteTopic(new DeleteTopicRequest(topic.getTopicArn()));
} catch (Exception e) {
AwsToolkitCore.getDefault().reportException("Unable to delete Amazon SNS topic", e);
}
}
ContentProviderRegistry.refreshAllContentProviders();
}
}
public static class CreateTopicAction extends Action {
public CreateTopicAction() {
this.setText("Create New Topic");
this.setToolTipText("Create a new Amazon SNS Topic");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD));
}
@Override
public void run() {
WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), new CreateTopicWizard());
dialog.open();
}
}
}
| 7,803 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/PublishMessageAction.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sns;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.Topic;
final class PublishMessageAction extends Action {
private final Topic topic;
private final AmazonSNS sns;
public PublishMessageAction(AmazonSNS sns, Topic topic) {
this.sns = sns;
this.topic = topic;
this.setText("Publish Message");
this.setToolTipText("Publish a message to this topic");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_PUBLISH));
}
@Override
public void run() {
PublishMessageAction.NewMessageDialog newMessageDialog = new NewMessageDialog();
if (newMessageDialog.open() == 0) {
String topicArn = topic.getTopicArn();
String subject = newMessageDialog.getSelectedSubject();
String message = newMessageDialog.getSelectedMessage();
try {
sns.publish(new PublishRequest(topicArn, message, subject));
} catch (Exception e) {
AwsToolkitCore.getDefault().reportException("Unable to publish message", e);
}
}
}
private static class NewMessageDialog extends MessageDialog {
private Text subjectText;
private Text messageText;
private String selectedSubject;
private String selectedMessage;
public NewMessageDialog() {
super(Display.getDefault().getActiveShell(),
"Publish New Message",
AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON),
"Enter the subject and message body to send to the subscribers of this topic.",
MessageDialog.INFORMATION,
new String[] {"OK", "Cancel"},
0);
}
public String getSelectedMessage() {
return selectedMessage;
}
public String getSelectedSubject() {
return selectedSubject;
}
private void updateControls() {
selectedMessage = messageText.getText();
selectedSubject = subjectText.getText();
boolean finished = (selectedMessage.length() > 0 &&
selectedSubject.length() > 0);
if (getButton(0) != null) getButton(0).setEnabled(finished);
}
@Override
protected Control createCustomArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
new Label(composite, SWT.NONE).setText("Subject:");
subjectText = new Text(composite, SWT.BORDER);
subjectText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
subjectText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateControls();
}
});
Label messageLabel = new Label(composite, SWT.NONE);
messageLabel.setText("Message:");
messageLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
messageText = new Text(composite, SWT.BORDER | SWT.MULTI);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.heightHint = 100;
messageText.setLayoutData(gridData);
messageText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateControls();
}
});
updateControls();
return composite;
}
}
}
| 7,804 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/SNSLabelProvider.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sns;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider;
import com.amazonaws.eclipse.explorer.sns.SNSContentProvider.SNSRootElement;
public class SNSLabelProvider extends ExplorerNodeLabelProvider {
@Override
public String getText(Object element) {
if (element instanceof SNSRootElement) return "Amazon SNS";
return getExplorerNodeText(element);
}
@Override
public Image getDefaultImage(Object element) {
if (element instanceof SNSRootElement) {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_SNS_SERVICE);
} else {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_TOPIC);
}
}
}
| 7,805 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/NewSubscriptionAction.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sns;
import java.util.LinkedHashMap;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.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.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.SubscribeRequest;
import com.amazonaws.services.sns.model.Topic;
class NewSubscriptionAction extends Action {
private final AmazonSNS sns;
private final Topic topic;
private final IRefreshable refreshable;
public NewSubscriptionAction(AmazonSNS sns, Topic topic, IRefreshable refreshable) {
this.sns = sns;
this.topic = topic;
this.refreshable = refreshable;
this.setText("Create Subscription");
this.setToolTipText("Create a new subscription for this topic");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD));
}
private class NewSubscriptionDialog extends MessageDialog {
private Label endpointLabel;
private Combo protocolCombo;
private Text endpointText;
private String selectedProtocol;
private String selectedEndpoint;
public NewSubscriptionDialog() {
super(Display.getDefault().getActiveShell(),
"Create New Subscription",
AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON),
"Select the message delivery protocol and details for a new subscription to this topic.",
MessageDialog.INFORMATION,
new String[] {"OK", "Cancel"},
0);
}
public String getSelectedProtocol() {
return selectedProtocol;
}
public String getSelectedEndpoint() {
return selectedEndpoint;
}
private void updateControls() {
selectedProtocol = (String)protocolCombo.getData(protocolCombo.getText());
selectedEndpoint = endpointText.getText();
boolean finished = (selectedProtocol.length() > 0 &&
selectedEndpoint.length() > 0);
if (getButton(0) != null) getButton(0).setEnabled(finished);
}
@Override
protected Control createCustomArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
new Label(composite, SWT.NONE).setText("Subscription Protocol:");
protocolCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
protocolCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
LinkedHashMap<String, String> protocolMap = new LinkedHashMap<>();
protocolMap.put("Email (plain text)", "email");
protocolMap.put("Email (JSON)", "email-json");
protocolMap.put("SQS", "sqs");
protocolMap.put("HTTP", "http");
protocolMap.put("HTTPS", "https");
protocolCombo.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
updateControls();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
});
for (String label : protocolMap.keySet()) {
protocolCombo.add(label);
protocolCombo.setData(label, protocolMap.get(label));
}
protocolCombo.select(0);
endpointLabel = new Label(composite, SWT.NONE);
endpointLabel.setText("Endpoint:");
endpointText = new Text(composite, SWT.BORDER);
endpointText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
endpointText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateControls();
}
});
updateControls();
return composite;
}
}
@Override
public void run() {
NewSubscriptionDialog newSubscriptionDialog = new NewSubscriptionDialog();
if (newSubscriptionDialog.open() == 0) {
String protocol = newSubscriptionDialog.getSelectedProtocol();
String endpoint = newSubscriptionDialog.getSelectedEndpoint();
try {
sns.subscribe(new SubscribeRequest(topic.getTopicArn(), protocol, endpoint));
} catch (Exception e) {
AwsToolkitCore.getDefault().reportException("Unable to subscribe to topic", e);
}
if (refreshable != null) refreshable.refreshData();
}
}
}
| 7,806 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/OpenTopicEditorAction.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sns;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.services.sns.model.Topic;
public class OpenTopicEditorAction extends Action {
private final Topic topic;
public OpenTopicEditorAction(Topic topic) {
this.setText("Open in SNS Topic Editor");
this.topic = topic;
}
@Override
public void run() {
String endpoint = RegionUtils.getCurrentRegion().getServiceEndpoints()
.get(ServiceAbbreviations.SNS);
String accountId = AwsToolkitCore.getDefault().getCurrentAccountId();
final IEditorInput input = new TopicEditorInput(topic, endpoint, accountId);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
activeWindow.getActivePage().openEditor(input, "com.amazonaws.eclipse.explorer.sns.topicEditor");
} catch (PartInitException e) {
AwsToolkitCore.getDefault().reportException("Unable to open the Amazon SNS topic editor", e);
}
}
});
}
}
| 7,807 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/OpenStreamingDistributionEditorAction.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.ui.IEditorInput;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.services.cloudfront.model.StreamingDistributionSummary;
public class OpenStreamingDistributionEditorAction extends AbstractOpenAwsEditorAction {
private StreamingDistributionSummary streamingDistributionSummary;
public OpenStreamingDistributionEditorAction(StreamingDistributionSummary distributionSummary) {
super("CloudFront Streaming Distribution Editor",
"com.amazonaws.eclipse.explorer.cloudfront.streamingDistributionEditor",
ServiceAbbreviations.CLOUDFRONT);
this.streamingDistributionSummary = distributionSummary;
}
@Override
public IEditorInput createEditorInput(String endpoint, String accountId) {
return new StreamingDistributionEditorInput(streamingDistributionSummary, endpoint, accountId);
}
}
| 7,808 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/CloudFrontActions.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.services.cloudfront.AmazonCloudFront;
import com.amazonaws.services.cloudfront.model.DistributionConfig;
import com.amazonaws.services.cloudfront.model.GetDistributionConfigRequest;
import com.amazonaws.services.cloudfront.model.GetDistributionConfigResult;
import com.amazonaws.services.cloudfront.model.GetStreamingDistributionConfigRequest;
import com.amazonaws.services.cloudfront.model.GetStreamingDistributionConfigResult;
import com.amazonaws.services.cloudfront.model.StreamingDistributionConfig;
import com.amazonaws.services.cloudfront.model.UpdateDistributionRequest;
import com.amazonaws.services.cloudfront.model.UpdateStreamingDistributionRequest;
public class CloudFrontActions {
private static abstract class AbstractDistributionStateChangingAction extends Action {
protected final String accountId;
protected final String distributionId;
private final IRefreshable refreshable;
public AbstractDistributionStateChangingAction(String distributionId, String accountId, IRefreshable refreshable) {
this.distributionId = distributionId;
this.accountId = accountId;
this.refreshable = refreshable;
this.setDisabledImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_GREY_CIRCLE));
}
protected AmazonCloudFront getClient() {
return AwsToolkitCore.getDefault().getClientFactory(accountId).getCloudFrontClient();
}
public abstract boolean isEnablingDistribution();
public abstract void updateDistributionConfig();
@Override
public void run() {
new Job("Updating distribution status") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
updateDistributionConfig();
if (refreshable != null) refreshable.refreshData();
} catch (Exception e) {
return new Status(Status.ERROR, AwsToolkitCore.getDefault().getPluginId(), "Unable to update distribution status", e);
}
return Status.OK_STATUS;
}
}.schedule();
}
}
private static abstract class StreamingDistributionStateChangingAction extends AbstractDistributionStateChangingAction {
public StreamingDistributionStateChangingAction(String distributionId, String accountId, IRefreshable refreshable) {
super(distributionId, accountId, refreshable);
}
@Override
public void updateDistributionConfig() {
AmazonCloudFront cf = getClient();
GetStreamingDistributionConfigResult distributionConfigResult =
cf.getStreamingDistributionConfig(new GetStreamingDistributionConfigRequest(distributionId));
StreamingDistributionConfig distributionConfig = distributionConfigResult.getStreamingDistributionConfig();
distributionConfig.setEnabled(isEnablingDistribution());
cf.updateStreamingDistribution(new UpdateStreamingDistributionRequest()
.withIfMatch(distributionConfigResult.getETag())
.withStreamingDistributionConfig(distributionConfig)
.withId(distributionId));
}
}
private static abstract class DistributionStateChangingAction extends AbstractDistributionStateChangingAction {
public DistributionStateChangingAction(String distributionId, String accountId, IRefreshable refreshable) {
super(distributionId, accountId, refreshable);
}
@Override
public void updateDistributionConfig() {
AmazonCloudFront cf = getClient();
GetDistributionConfigResult distributionConfigResult =
cf.getDistributionConfig(new GetDistributionConfigRequest(distributionId));
DistributionConfig distributionConfig = distributionConfigResult.getDistributionConfig();
distributionConfig.setEnabled(isEnablingDistribution());
cf.updateDistribution(new UpdateDistributionRequest()
.withIfMatch(distributionConfigResult.getETag())
.withDistributionConfig(distributionConfig)
.withId(distributionId));
}
}
public static class EnableStreamingDistributionAction extends StreamingDistributionStateChangingAction {
public EnableStreamingDistributionAction(String distributionId, String accountId, IRefreshable refreshable) {
super(distributionId, accountId, refreshable);
this.setText("Enable");
this.setToolTipText("Enable this streaming distribution");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_GREEN_CIRCLE));
}
@Override
public boolean isEnablingDistribution() {
return true;
}
}
public static class DisableStreamingDistributionAction extends StreamingDistributionStateChangingAction {
public DisableStreamingDistributionAction(String distributionId, String accountId, IRefreshable refreshable) {
super(distributionId, accountId, refreshable);
this.setText("Disable");
this.setToolTipText("Disable this streaming distribution");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_RED_CIRCLE));
}
@Override
public boolean isEnablingDistribution() {
return false;
}
}
public static class EnableDistributionAction extends DistributionStateChangingAction {
public EnableDistributionAction(String distributionId, String accountId, IRefreshable refreshable) {
super(distributionId, accountId, refreshable);
this.setText("Enable");
this.setToolTipText("Enable this distribution");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_GREEN_CIRCLE));
}
@Override
public boolean isEnablingDistribution() {
return true;
}
}
public static class DisableDistributionAction extends DistributionStateChangingAction {
public DisableDistributionAction(String distributionId, String accountId, IRefreshable refreshable) {
super(distributionId, accountId, refreshable);
this.setText("Disable");
this.setToolTipText("Disable this distribution");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_RED_CIRCLE));
}
@Override
public boolean isEnablingDistribution() {
return false;
}
}
}
| 7,809 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/CloudFrontLabelProvider.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider;
import com.amazonaws.eclipse.explorer.cloudfront.CloudFrontContentProvider.CloudFrontRootElement;
public class CloudFrontLabelProvider extends ExplorerNodeLabelProvider {
@Override
public String getText(Object element) {
if (element instanceof CloudFrontRootElement) return "Amazon CloudFront";
return getExplorerNodeText(element);
}
@Override
public Image getDefaultImage(Object element) {
if (element instanceof CloudFrontRootElement) {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_CLOUDFRONT_SERVICE);
} else {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_DISTRIBUTION);
}
}
}
| 7,810 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/CloudFrontContentProvider.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
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;
import com.amazonaws.services.cloudfront.AmazonCloudFront;
import com.amazonaws.services.cloudfront.model.DistributionList;
import com.amazonaws.services.cloudfront.model.DistributionSummary;
import com.amazonaws.services.cloudfront.model.ListDistributionsRequest;
import com.amazonaws.services.cloudfront.model.ListStreamingDistributionsRequest;
import com.amazonaws.services.cloudfront.model.StreamingDistributionList;
import com.amazonaws.services.cloudfront.model.StreamingDistributionSummary;
public class CloudFrontContentProvider extends AbstractContentProvider {
public static class CloudFrontRootElement {
public static final CloudFrontRootElement ROOT_ELEMENT = new CloudFrontRootElement();
}
public static class StreamingDistributionNode extends ExplorerNode {
private final StreamingDistributionSummary distributionSummary;
public StreamingDistributionNode(StreamingDistributionSummary distributionSummary) {
super(distributionSummary.getDomainName(), 0,
loadImage(AwsToolkitCore.IMAGE_STREAMING_DISTRIBUTION),
new OpenStreamingDistributionEditorAction(distributionSummary));
this.distributionSummary = distributionSummary;
}
public StreamingDistributionSummary getDistributionSummary() {
return distributionSummary;
}
}
public static class DistributionNode extends ExplorerNode {
private final DistributionSummary distributionSummary;
public DistributionNode(DistributionSummary distributionSummary) {
super(distributionSummary.getDomainName(), 0,
loadImage(AwsToolkitCore.IMAGE_DISTRIBUTION),
new OpenDistributionEditorAction(distributionSummary));
this.distributionSummary = distributionSummary;
}
public DistributionSummary getDistributionSummary() {
return distributionSummary;
}
}
@Override
public boolean hasChildren(Object element) {
return (element instanceof CloudFrontRootElement);
}
@Override
public Object[] loadChildren(Object parentElement) {
if (parentElement instanceof AWSResourcesRootElement) {
return new Object[] { CloudFrontRootElement.ROOT_ELEMENT };
}
if (parentElement instanceof CloudFrontRootElement) {
new DataLoaderThread(parentElement) {
@Override
public Object[] loadData() {
AmazonCloudFront cf = AwsToolkitCore.getClientFactory().getCloudFrontClient();
List<ExplorerNode> distributionNodes = new ArrayList<>();
DistributionList distributionList = null;
do {
ListDistributionsRequest request = new ListDistributionsRequest();
if (distributionList != null) request.setMarker(distributionList.getNextMarker());
distributionList = cf.listDistributions(request).getDistributionList();
for (DistributionSummary distributionSummary : distributionList.getItems()) {
distributionNodes.add(new DistributionNode(distributionSummary));
}
} while (distributionList.isTruncated());
StreamingDistributionList streamingDistributionList = null;
do {
ListStreamingDistributionsRequest request = new ListStreamingDistributionsRequest();
if (streamingDistributionList != null) request.setMarker(streamingDistributionList.getNextMarker());
streamingDistributionList = cf.listStreamingDistributions(request).getStreamingDistributionList();
for (StreamingDistributionSummary distributionSummary : streamingDistributionList.getItems()) {
distributionNodes.add(new StreamingDistributionNode(distributionSummary));
}
} while (streamingDistributionList.isTruncated());
return distributionNodes.toArray();
}
}.start();
}
return Loading.LOADING;
}
@Override
public String getServiceAbbreviation() {
return ServiceAbbreviations.CLOUDFRONT;
}
}
| 7,811 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/DistributionEditor.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import com.amazonaws.eclipse.explorer.cloudfront.CloudFrontActions.DisableDistributionAction;
import com.amazonaws.eclipse.explorer.cloudfront.CloudFrontActions.EnableDistributionAction;
import com.amazonaws.services.cloudfront.model.Distribution;
import com.amazonaws.services.cloudfront.model.DistributionConfig;
import com.amazonaws.services.cloudfront.model.GetDistributionRequest;
public class DistributionEditor extends AbstractDistributionEditor {
private DistributionEditorInput editorInput;
private EnableDistributionAction enableDistributionAction;
private DisableDistributionAction disableDistributionAction;
@Override
public void refreshData() {
new LoadDistributionInfoThread().start();
}
@Override
protected String getResourceTitle() {
return "Distribution";
}
@Override
protected void contributeActions(IToolBarManager toolbarManager) {
enableDistributionAction = new EnableDistributionAction(editorInput.getDistributionId(), editorInput.getAccountId(), this);
disableDistributionAction = new DisableDistributionAction(editorInput.getDistributionId(), editorInput.getAccountId(), this);
toolbarManager.add(enableDistributionAction);
toolbarManager.add(disableDistributionAction);
}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
super.init(site, input);
this.editorInput = (DistributionEditorInput)input;
}
private class LoadDistributionInfoThread extends ResourceEditorDataLoaderThread {
@Override
public void loadData() {
final Distribution distribution = getClient().getDistribution(new GetDistributionRequest(editorInput.getDistributionId())).getDistribution();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
setText(domainNameText, distribution.getDomainName());
setText(distributionIdText, distribution.getId());
setText(lastModifiedText, distribution.getLastModifiedTime());
setText(statusText, distribution.getStatus());
DistributionConfig distributionConfig = distribution.getDistributionConfig();
setText(enabledText, distributionConfig.getEnabled());
setText(commentText, distributionConfig.getComment());
setText(defaultRootObjectLabel, distributionConfig.getDefaultRootObject());
cnamesList.removeAll();
for (String cname : distributionConfig.getAliases().getItems()) {
cnamesList.add(cname);
}
if (distributionConfig.getLogging() != null) {
setText(loggingEnabledText, "Yes");
setText(loggingBucketText, distributionConfig.getLogging().getBucket());
setText(loggingPrefixText, distributionConfig.getLogging().getPrefix());
} else {
setText(loggingEnabledText, "No");
loggingBucketText.setText("N/A");
loggingPrefixText.setText("N/A");
}
if (!distributionConfig.getOrigins().getItems().isEmpty()) {
setText(originText, distributionConfig.getOrigins().getItems().get(0).getDomainName());
} else {
originText.setText("N/A");
}
enableDistributionAction.setEnabled(distributionConfig.isEnabled() == false);
disableDistributionAction.setEnabled(distributionConfig.isEnabled() == true);
updateToolbar();
}
});
}
}
}
| 7,812 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/StreamingDistributionEditorInput.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.jface.resource.ImageDescriptor;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput;
import com.amazonaws.services.cloudfront.model.StreamingDistributionSummary;
public class StreamingDistributionEditorInput extends AbstractAwsResourceEditorInput {
private final StreamingDistributionSummary distributionSummary;
public StreamingDistributionEditorInput(StreamingDistributionSummary distributionSummary, String regionEndpoint, String accountId) {
super(regionEndpoint, accountId);
this.distributionSummary = distributionSummary;
}
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_STREAMING_DISTRIBUTION);
}
@Override
public String getName() {
return getDistributionId();
}
public String getDistributionId() {
return distributionSummary.getId();
}
public StreamingDistributionSummary getDistributionSummary() {
return distributionSummary;
}
@Override
public String getToolTipText() {
return "Amazon CloudFront Distribution Editor - " + getName();
}
}
| 7,813 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/DistributionDecorator.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.jface.viewers.IDecoration;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ILightweightLabelDecorator;
import com.amazonaws.eclipse.explorer.cloudfront.CloudFrontContentProvider.DistributionNode;
import com.amazonaws.eclipse.explorer.cloudfront.CloudFrontContentProvider.StreamingDistributionNode;
import com.amazonaws.services.cloudfront.model.Origins;
import com.amazonaws.services.cloudfront.model.S3Origin;
public class DistributionDecorator implements ILightweightLabelDecorator {
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public void removeListener(ILabelProviderListener listener) {}
@Override
public void dispose() {}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void decorate(Object element, IDecoration decoration) {
if (element instanceof DistributionNode) {
DistributionNode distributionNode = (DistributionNode)element;
String origin = createOriginString(
distributionNode.getDistributionSummary().getOrigins());
decoration.addSuffix(" " + origin);
} else if (element instanceof StreamingDistributionNode) {
StreamingDistributionNode distributionNode = (StreamingDistributionNode)element;
String origin = createOriginString(
distributionNode.getDistributionSummary().getS3Origin());
decoration.addSuffix(" " + origin);
}
}
private String createOriginString(Origins origins) {
if (origins == null || origins.getItems().isEmpty()) {
return null;
}
return origins.getItems().get(0).getDomainName();
}
private String createOriginString(S3Origin s3Origin) {
if (s3Origin != null) {
return s3Origin.getDomainName();
}
return null;
}
}
| 7,814 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/StreamingDistributionEditor.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import com.amazonaws.eclipse.explorer.cloudfront.CloudFrontActions.DisableStreamingDistributionAction;
import com.amazonaws.eclipse.explorer.cloudfront.CloudFrontActions.EnableStreamingDistributionAction;
import com.amazonaws.services.cloudfront.model.GetStreamingDistributionRequest;
import com.amazonaws.services.cloudfront.model.StreamingDistribution;
import com.amazonaws.services.cloudfront.model.StreamingDistributionConfig;
public class StreamingDistributionEditor extends AbstractDistributionEditor {
private StreamingDistributionEditorInput editorInput;
private EnableStreamingDistributionAction enableDistributionAction;
private DisableStreamingDistributionAction disableDistributionAction;
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
super.init(site, input);
editorInput = (StreamingDistributionEditorInput)input;
}
@Override
public void refreshData() {
new LoadDistributionInfoThread().start();
}
@Override
protected boolean supportsDefaultRootObjects() {
return false;
}
@Override
protected String getResourceTitle() {
return "Streaming Distribution";
}
@Override
protected void contributeActions(IToolBarManager toolbarManager) {
enableDistributionAction = new EnableStreamingDistributionAction(editorInput.getDistributionId(), editorInput.getAccountId(), this);
disableDistributionAction = new DisableStreamingDistributionAction(editorInput.getDistributionId(), editorInput.getAccountId(), this);
toolbarManager.add(enableDistributionAction);
toolbarManager.add(disableDistributionAction);
}
private class LoadDistributionInfoThread extends ResourceEditorDataLoaderThread {
@Override
public void loadData() {
final StreamingDistribution distribution = getClient().getStreamingDistribution(new GetStreamingDistributionRequest(editorInput.getDistributionId())).getStreamingDistribution();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
setText(domainNameText, distribution.getDomainName());
setText(distributionIdText, distribution.getId());
setText(lastModifiedText, distribution.getLastModifiedTime());
setText(statusText, distribution.getStatus());
StreamingDistributionConfig distributionConfig = distribution.getStreamingDistributionConfig();
setText(commentText, distributionConfig.getComment());
setText(originText, distributionConfig.getS3Origin().getDomainName());
setText(enabledText, distributionConfig.getEnabled());
cnamesList.removeAll();
for (String cname : distributionConfig.getAliases().getItems()) {
cnamesList.add(cname);
}
if (distributionConfig.getLogging() != null) {
setText(loggingEnabledText, "Yes");
setText(loggingBucketText, distributionConfig.getLogging().getBucket());
setText(loggingPrefixText, distributionConfig.getLogging().getPrefix());
} else {
setText(loggingEnabledText, "No");
loggingBucketText.setText("N/A");
loggingPrefixText.setText("N/A");
}
enableDistributionAction.setEnabled(distributionConfig.isEnabled() == false);
disableDistributionAction.setEnabled(distributionConfig.isEnabled() == true);
updateToolbar();
}
});
}
}
}
| 7,815 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/OpenDistributionEditorAction.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.ui.IEditorInput;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.services.cloudfront.model.DistributionSummary;
public class OpenDistributionEditorAction extends AbstractOpenAwsEditorAction {
private DistributionSummary distributionSummary;
public OpenDistributionEditorAction(DistributionSummary distributionSummary) {
super("CloudFront Distribution Editor",
"com.amazonaws.eclipse.explorer.cloudfront.distributionEditor",
ServiceAbbreviations.CLOUDFRONT);
this.distributionSummary = distributionSummary;
}
@Override
public IEditorInput createEditorInput(String endpoint, String accountId) {
return new DistributionEditorInput(distributionSummary, endpoint, accountId);
}
}
| 7,816 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/DistributionEditorInput.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.jface.resource.ImageDescriptor;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput;
import com.amazonaws.services.cloudfront.model.DistributionSummary;
public class DistributionEditorInput extends AbstractAwsResourceEditorInput {
private final DistributionSummary distributionSummary;
public DistributionEditorInput(DistributionSummary distributionSummary, String regionEndpoint, String accountId) {
super(regionEndpoint, accountId);
this.distributionSummary = distributionSummary;
}
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_DISTRIBUTION);
}
@Override
public String getName() {
return getDistributionId();
}
public String getDistributionId() {
return distributionSummary.getId();
}
public DistributionSummary getDistributionSummary() {
return distributionSummary;
}
@Override
public String getToolTipText() {
return "Amazon CloudFront Distribution Editor - " + getName();
}
}
| 7,817 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/ResourceEditorDataLoaderThread.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.util.DateUtils;
public abstract class ResourceEditorDataLoaderThread extends Thread {
public abstract void loadData();
@Override
public void run() {
try {
loadData();
} catch (Exception e) {
AwsToolkitCore.getDefault().logError("Unable to load resource information", e);
}
}
protected void setText(Text label, Date value) {
if (value == null) {
label.setText("");
} else {
label.setText(DateUtils.formatRFC822Date(value));
}
}
protected void setText(Text label, Boolean value) {
if (value == null) label.setText("");
else if (value) label.setText("Yes");
else label.setText("No");
}
protected void setText(Text label, String value) {
if (value == null) label.setText("");
else label.setText(value);
}
protected void setText(Text label, List<String> value) {
if (value == null) value = new ArrayList<>(0);
StringBuilder buffer = new StringBuilder();
for (String s : value) {
if (buffer.length() > 0) buffer.append(", ");
buffer.append(s);
}
label.setText(buffer.toString());
}
protected void setText(Text label, Map<String, String> map, String key) {
if (map.get(key) == null) label.setText("");
else label.setText(map.get(key));
}
protected void setText(Label label, Date value) {
if (value == null) {
label.setText("");
} else {
label.setText(DateUtils.formatRFC822Date(value));
}
}
protected void setText(Label label, Boolean value) {
if (value == null) label.setText("");
else label.setText(value.toString());
}
protected void setText(Label label, String value) {
if (value == null) label.setText("");
else label.setText(value);
}
protected void setText(Label label, List<String> value) {
if (value == null) value = new ArrayList<>(0);
StringBuilder buffer = new StringBuilder();
for (String s : value) {
if (buffer.length() > 0) buffer.append(", ");
buffer.append(s);
}
label.setText(buffer.toString());
}
protected void setText(Label label, Map<String, String> map, String key) {
if (map.get(key) == null) label.setText("");
else label.setText(map.get(key));
}
}
| 7,818 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/AbstractDistributionEditor.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.layout.GridDataFactory;
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.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.part.EditorPart;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput;
import com.amazonaws.services.cloudfront.AmazonCloudFront;
public abstract class AbstractDistributionEditor extends EditorPart implements IRefreshable {
private static final String ACCESS_LOGGING_DOCUMENTATION_URL = "http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html";
private static final String CNAME_DOCUMENTATION_URL = "http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html";
private AbstractAwsResourceEditorInput editorInput;
protected Text domainNameText;
protected Text distributionIdText;
protected Text lastModifiedText;
protected Text enabledText;
protected Text statusText;
protected Text commentText;
protected Label defaultRootObjectLabel;
protected Text originText;
protected Text loggingEnabledText;
protected Text loggingBucketText;
protected Text loggingPrefixText;
protected org.eclipse.swt.widgets.List cnamesList;
private ScrolledForm form;
protected boolean supportsDefaultRootObjects() {
return true;
}
protected abstract void contributeActions(IToolBarManager iToolBarManager);
protected abstract String getResourceTitle();
@Override
public void doSave(IProgressMonitor monitor) {}
@Override
public void doSaveAs() {}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void setFocus() {}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
setPartName(input.getName());
this.editorInput = (AbstractAwsResourceEditorInput)input;
}
@Override
public void createPartControl(Composite parent) {
FormToolkit toolkit = new FormToolkit(Display.getDefault());
form = toolkit.createScrolledForm(parent);
form.setFont(JFaceResources.getHeaderFont());
form.setText(getResourceTitle() + " " + editorInput.getName());
toolkit.decorateFormHeading(form.getForm());
form.setImage(getTitleImage());
form.getBody().setLayout(new GridLayout());
createDistributionSummaryComposite(toolkit, form.getBody());
form.reflow(true);
refreshData();
contributeActions(form.getToolBarManager());
form.getToolBarManager().add(new Separator());
form.getToolBarManager().add(new RefreshAction());
form.getToolBarManager().update(true);
}
protected void createDistributionSummaryComposite(FormToolkit toolkit, Composite parent) {
GridDataFactory gdf = GridDataFactory.swtDefaults()
.align(SWT.FILL, SWT.TOP)
.grab(true, false);
GridDataFactory sectionGDF = GridDataFactory.swtDefaults()
.span(2, 1)
.grab(true, false)
.align(SWT.FILL, SWT.TOP)
.indent(0, 10);
Composite summaryComposite = toolkit.createComposite(parent);
summaryComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
summaryComposite.setLayout(new GridLayout(2, false));
toolkit.createLabel(summaryComposite, "Domain Name:");
domainNameText = createText(summaryComposite);
gdf.applyTo(domainNameText);
toolkit.createLabel(summaryComposite, "Distribution ID:");
distributionIdText = createText(summaryComposite);
gdf.applyTo(distributionIdText);
toolkit.createLabel(summaryComposite, "Origin:");
originText = createText(summaryComposite);
gdf.applyTo(originText);
toolkit.createLabel(summaryComposite, "Enabled:");
enabledText = createText(summaryComposite);
gdf.applyTo(enabledText);
toolkit.createLabel(summaryComposite, "Status:");
statusText = createText(summaryComposite);
gdf.applyTo(statusText);
toolkit.createLabel(summaryComposite, "Last Modified:");
lastModifiedText = createText(summaryComposite);
gdf.applyTo(lastModifiedText);
toolkit.createLabel(summaryComposite, "Comment:");
commentText = createText(summaryComposite);
gdf.applyTo(commentText);
if (supportsDefaultRootObjects()) {
toolkit.createLabel(summaryComposite, "Default Root Object:");
defaultRootObjectLabel = toolkit.createLabel(summaryComposite, "");
gdf.applyTo(defaultRootObjectLabel);
}
// Logging
Section loggingSection = toolkit.createSection(summaryComposite, Section.EXPANDED | Section.TITLE_BAR);
loggingSection.setText("Access Logging:");
Composite loggingComposite = toolkit.createComposite(loggingSection);
loggingSection.setClient(loggingComposite);
loggingComposite.setLayout(new GridLayout(2, false));
sectionGDF.applyTo(loggingSection);
toolkit.createLabel(loggingComposite, "Logging Enabled:");
loggingEnabledText = createText(loggingComposite);
toolkit.createLabel(loggingComposite, "Destination Bucket:");
loggingBucketText = createText(loggingComposite);
gdf.applyTo(loggingBucketText);
toolkit.createLabel(loggingComposite, "Log File Prefix:");
loggingPrefixText = createText(loggingComposite);
gdf.applyTo(loggingPrefixText);
WebLinkListener webLinkListener = new WebLinkListener();
createVerticalSpacer(loggingComposite);
createLink(loggingComposite, webLinkListener, "Amazon CloudFront provides optional log files with information about end user access to your objects.");
createLink(loggingComposite, webLinkListener, "For more information, see the <A HREF=\"" + ACCESS_LOGGING_DOCUMENTATION_URL + "\">Access Logs for Distributions</A> section in the Amazon CloudFront documentation.");
// CNAMEs
Section cnamesSection = toolkit.createSection(summaryComposite, Section.EXPANDED | Section.TITLE_BAR);
Composite cnamesComposite = toolkit.createComposite(cnamesSection);
cnamesSection.setClient(cnamesComposite);
sectionGDF.applyTo(cnamesSection);
cnamesSection.setText("CNAME Aliases:");
cnamesComposite.setLayout(new GridLayout(2, false));
cnamesList = new org.eclipse.swt.widgets.List(cnamesComposite, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL);
gdf.applyTo(cnamesList);
((GridData)cnamesList.getLayoutData()).horizontalSpan = 2;
createVerticalSpacer(cnamesComposite);
createLink(cnamesComposite, webLinkListener, "A CNAME record lets you specify an alternate domain name for the domain name CloudFront provides for your distribution.");
createLink(cnamesComposite, webLinkListener, "For more information, see the <A HREF=\"" + CNAME_DOCUMENTATION_URL + "\">Using CNAMEs with Distributions</A> section in the Amazon CloudFront documentation.");
}
/*
* Utils
*/
protected AmazonCloudFront getClient() {
AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(editorInput.getAccountId());
return clientFactory.getCloudFrontClientByEndpoint(editorInput.getRegionEndpoint());
}
protected Text createText(Composite parent) {
Text text = new Text(parent, SWT.READ_ONLY);
text.setBackground(parent.getBackground());
text.setText("");
return text;
}
protected Link createLink(Composite parent, Listener linkListener, String linkText) {
Link link = new Link(parent, SWT.WRAP);
link.setText(linkText);
link.addListener(SWT.Selection, linkListener);
GridData data = new GridData(SWT.FILL, SWT.TOP, false, false);
data.horizontalSpan = 2;
data.widthHint = 100;
data.heightHint = 15;
link.setLayoutData(data);
return link;
}
protected Composite createVerticalSpacer(Composite parent) {
Composite spacer = new Composite(parent, SWT.NONE);
GridData data = new GridData(SWT.FILL, SWT.TOP, false, false);
spacer.setSize(SWT.DEFAULT, 5);
data.horizontalSpan = 2;
data.widthHint = 5;
data.heightHint = 5;
spacer.setLayoutData(data);
return spacer;
}
protected void updateToolbar() {
form.getToolBarManager().update(true);
}
protected final class RefreshAction extends Action {
public RefreshAction() {
this.setText("Refresh");
this.setToolTipText("Refresh distribution information");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH));
}
@Override
public void run() {
refreshData();
}
}
}
| 7,819 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/cloudfront/AbstractOpenAwsEditorAction.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudfront;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
public abstract class AbstractOpenAwsEditorAction extends Action {
private final String editorName;
private final String editorId;
private final String serviceAbbreviation;
public abstract IEditorInput createEditorInput(String endpoint, String accountId);
public AbstractOpenAwsEditorAction(String editorName, String editorId, String serviceAbbreviation) {
this.editorName = editorName;
this.editorId = editorId;
this.serviceAbbreviation = serviceAbbreviation;
this.setText("Open in " + editorName);
}
@Override
public void run() {
String endpoint = RegionUtils.getCurrentRegion().getServiceEndpoints().get(serviceAbbreviation);
String accountId = AwsToolkitCore.getDefault().getCurrentAccountId();
final IEditorInput input = createEditorInput(endpoint, accountId);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
activeWindow.getActivePage().openEditor(input, editorId);
} catch (PartInitException e) {
AwsToolkitCore.getDefault().logError("Unable to open the " + editorName, e);
}
}
});
}
}
| 7,820 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sqs/QueueAttributes.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sqs;
import com.amazonaws.services.sqs.model.QueueAttributeName;
public interface QueueAttributes {
public static String ALL = "All";
// Queue Attributes
public static String RETENTION_PERIOD = "MessageRetentionPeriod";
public static String MAX_MESSAGE_SIZE = "MaximumMessageSize";
public static String CREATED = "CreatedTimestamp";
public static String VISIBILITY_TIMEOUT = "VisibilityTimeout";
public static String ARN = "QueueArn";
public static String NUMBER_OF_MESSAGES = "ApproximateNumberOfMessages";
public static String DELAY_SECONDS = QueueAttributeName.DelaySeconds.toString();
// Message Attributes
public static String FIRST_RECEIVED = "ApproximateFirstReceiveTimestamp";
public static String RECEIVE_COUNT = "ApproximateReceiveCount";
public static String SENT = "SentTimestamp";
public static String SENDER_ID = "SenderId";
}
| 7,821 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sqs/QueueEditorInput.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sqs;
import org.eclipse.jface.resource.ImageDescriptor;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput;
public class QueueEditorInput extends AbstractAwsResourceEditorInput {
private final String queueUrl;
public QueueEditorInput(String queueUrl, String endpoint, String accountId) {
super(endpoint, accountId);
this.queueUrl = queueUrl;
}
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_QUEUE);
}
@Override
public String getName() {
int index = queueUrl.lastIndexOf('/');
if (index > 0) return queueUrl.substring(index + 1);
return queueUrl;
}
public String getQueueUrl() {
return queueUrl;
}
@Override
public String getToolTipText() {
return "Amazon SQS Queue Editor - " + getName();
}
}
| 7,822 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sqs/QueueEditor.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sqs;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.ALL;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.ARN;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.CREATED;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.DELAY_SECONDS;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.MAX_MESSAGE_SIZE;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.NUMBER_OF_MESSAGES;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.RETENTION_PERIOD;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.SENDER_ID;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.SENT;
import static com.amazonaws.eclipse.explorer.sqs.QueueAttributes.VISIBILITY_TIMEOUT;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreePathContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
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.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.part.EditorPart;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
public class QueueEditor extends EditorPart implements IRefreshable {
private QueueEditorInput queueEditorInput;
private Text retentionPeriodLabel;
private Text maxMessageSizeLabel;
private Text createdLabel;
private Text visibilityTimeoutLabel;
private Text queueArnLabel;
private Text numberOfMessagesLabel;
private TreeViewer viewer;
private Text queueDelayLabel;
@Override
public void doSave(IProgressMonitor arg0) {}
@Override
public void doSaveAs() {}
@Override
public void setFocus() {}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
setPartName(input.getName());
queueEditorInput = (QueueEditorInput)input;
}
@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(queueEditorInput.getName());
toolkit.decorateFormHeading(form.getForm());
form.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_QUEUE));
form.getBody().setLayout(new GridLayout());
createQueueSummaryInfoSection(form, toolkit);
createMessageList(form, toolkit);
form.getToolBarManager().add(new RefreshAction());
form.getToolBarManager().add(new Separator());
form.getToolBarManager().add(new AddMessageAction(getClient(), queueEditorInput.getQueueUrl(), this));
form.getToolBarManager().update(true);
}
private class DeleteMessageAction extends Action {
public DeleteMessageAction() {
this.setText("Delete");
this.setToolTipText("Delete this message from the queue");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE));
}
@Override
public boolean isEnabled() {
return !viewer.getSelection().isEmpty();
}
@Override
public void run() {
StructuredSelection selection = (StructuredSelection)viewer.getSelection();
Iterator<Message> iterator = selection.iterator();
while (iterator.hasNext()) {
Message message = iterator.next();
getClient().deleteMessage(new DeleteMessageRequest(queueEditorInput.getQueueUrl(), message.getReceiptHandle()));
}
new RefreshAction().run();
}
}
private class RefreshAction extends Action {
public RefreshAction() {
this.setText("Refresh");
this.setToolTipText("Refresh queue message sampling");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH));
}
@Override
public void run() {
new LoadMessagesThread().start();
new LoadQueueAttributesThread().start();
}
}
private void createQueueSummaryInfoSection(final ScrolledForm form, final FormToolkit toolkit) {
GridDataFactory gridDataFactory = GridDataFactory.swtDefaults().align(SWT.FILL, SWT.TOP).grab(true, false).minSize(200, SWT.DEFAULT).hint(200, SWT.DEFAULT);
Composite composite = toolkit.createComposite(form.getBody());
composite.setLayout(new GridLayout(2, false));
composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
toolkit.createLabel(composite, "Retention Period:");
retentionPeriodLabel = toolkit.createText(composite, "", SWT.READ_ONLY);
gridDataFactory.applyTo(retentionPeriodLabel);
toolkit.createLabel(composite, "Max Message Size:");
maxMessageSizeLabel = toolkit.createText(composite, "", SWT.READ_ONLY);
gridDataFactory.applyTo(maxMessageSizeLabel);
toolkit.createLabel(composite, "Created:");
createdLabel = toolkit.createText(composite, "", SWT.READ_ONLY);
gridDataFactory.applyTo(createdLabel);
toolkit.createLabel(composite, "Visibility Timeout:");
visibilityTimeoutLabel = toolkit.createText(composite, "", SWT.READ_ONLY);
gridDataFactory.applyTo(visibilityTimeoutLabel);
toolkit.createLabel(composite, "Queue ARN:");
queueArnLabel = toolkit.createText(composite, "", SWT.READ_ONLY);
gridDataFactory.applyTo(queueArnLabel);
toolkit.createLabel(composite, "Approx. Message Count:");
numberOfMessagesLabel = toolkit.createText(composite, "", SWT.READ_ONLY);
gridDataFactory.applyTo(numberOfMessagesLabel);
toolkit.createLabel(composite, "Message Delay (seconds):");
queueDelayLabel = toolkit.createText(composite, "", SWT.READ_ONLY);
gridDataFactory.applyTo(queueDelayLabel);
new LoadQueueAttributesThread().start();
}
private AmazonSQS getClient() {
AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(queueEditorInput.getAccountId());
return clientFactory.getSQSClientByEndpoint(queueEditorInput.getRegionEndpoint());
}
private class LoadQueueAttributesThread extends Thread {
@Override
public void run() {
GetQueueAttributesRequest request = new GetQueueAttributesRequest(queueEditorInput.getQueueUrl()).withAttributeNames(ALL);
final Map<String, String> attributes = getClient().getQueueAttributes(request).getAttributes();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
retentionPeriodLabel.setText(attributes.get(RETENTION_PERIOD));
maxMessageSizeLabel.setText(attributes.get(MAX_MESSAGE_SIZE));
createdLabel.setText(attributes.get(CREATED));
visibilityTimeoutLabel.setText(attributes.get(VISIBILITY_TIMEOUT));
queueArnLabel.setText(attributes.get(ARN));
numberOfMessagesLabel.setText(attributes.get(NUMBER_OF_MESSAGES));
queueDelayLabel.setText(valueOrDefault(attributes.get(DELAY_SECONDS), "0"));
numberOfMessagesLabel.getParent().layout();
}
});
}
private String valueOrDefault(String value, String defaultValue) {
if (value != null) return value;
else return defaultValue;
}
}
private class LoadMessagesThread extends Thread {
@Override
public void run() {
final Map<String, Message> messagesById = new HashMap<>();
for (int i = 0; i < 5; i++) {
ReceiveMessageRequest request = new ReceiveMessageRequest(queueEditorInput.getQueueUrl()).withVisibilityTimeout(0).withMaxNumberOfMessages(10).withAttributeNames(ALL);
List<Message> messages = getClient().receiveMessage(request).getMessages();
for (Message message : messages) {
messagesById.put(message.getMessageId(), message);
}
}
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(messagesById.values());
}
});
}
}
private final class MessageContentProvider implements ITreePathContentProvider {
private Message[] messages;
@Override
public void dispose() {}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof Collection) {
messages = ((Collection<Message>)newInput).toArray(new Message[0]);
} else {
messages = new Message[0];
}
}
@Override
public Object[] getChildren(TreePath arg0) {
return null;
}
@Override
public Object[] getElements(Object arg0) {
return messages;
}
@Override
public TreePath[] getParents(Object arg0) {
return new TreePath[0];
}
@Override
public boolean hasChildren(TreePath arg0) {
return false;
}
}
private final class MessageLabelProvider implements ITableLabelProvider {
private final DateFormat dateFormat;
public MessageLabelProvider() {
dateFormat = DateFormat.getDateTimeInstance();
}
@Override
public void addListener(ILabelProviderListener arg0) {}
@Override
public void removeListener(ILabelProviderListener arg0) {}
@Override
public void dispose() {}
@Override
public boolean isLabelProperty(Object obj, String column) {
return false;
}
@Override
public Image getColumnImage(Object obj, int column) {
return null;
}
@Override
public String getColumnText(Object obj, int column) {
if (obj instanceof Message == false) return "";
Message message = (Message)obj;
Map<String, String> attributes = message.getAttributes();
switch (column) {
case 0: return message.getMessageId();
case 1: return message.getBody();
case 2: return formatDate(attributes.get(SENT));
case 3: return attributes.get(SENDER_ID);
}
return "";
}
private String formatDate(String epochString) {
if (epochString == null || epochString.trim().length() == 0) return "";
long epochSeconds = Long.parseLong(epochString);
return dateFormat.format(new Date(epochSeconds));
}
}
private void createMessageList(final ScrolledForm form, final FormToolkit toolkit) {
Composite parent = toolkit.createComposite(form.getBody());
parent.setLayout(new GridLayout());
parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Label label = toolkit.createLabel(parent, "Message Sampling");
label.setFont(JFaceResources.getHeaderFont());
label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
label.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false));
Composite composite = toolkit.createComposite(parent);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TreeColumnLayout tableColumnLayout = new TreeColumnLayout();
composite.setLayout(tableColumnLayout);
MessageContentProvider contentProvider = new MessageContentProvider();
MessageLabelProvider labelProvider = new MessageLabelProvider();
viewer = new TreeViewer(composite, SWT.BORDER | SWT.MULTI);
viewer.getTree().setLinesVisible(true);
viewer.getTree().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTree());
viewer.setInput(new Object());
MenuManager menuManager = new MenuManager();
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
manager.add(new DeleteMessageAction());
}
});
Menu menu = menuManager.createContextMenu(viewer.getTree());
viewer.getTree().setMenu(menu);
getSite().registerContextMenu(menuManager, viewer);
new LoadMessagesThread().start();
}
private void createColumns(TreeColumnLayout columnLayout, Tree tree) {
createColumn(tree, columnLayout, "ID");
createColumn(tree, columnLayout, "Body");
createColumn(tree, columnLayout, "Sent");
createColumn(tree, columnLayout, "Sender");
}
private TreeColumn createColumn(Tree tree, TreeColumnLayout columnLayout, String text) {
TreeColumn column = new TreeColumn(tree, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
@Override
public void refreshData() {
new RefreshAction().run();
}
}
| 7,823 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sqs/OpenQueueEditorAction.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sqs;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
public class OpenQueueEditorAction extends Action {
private final String queueUrl;
public OpenQueueEditorAction(String queueUrl) {
this.setText("Open in SQS Queue Editor");
this.queueUrl = queueUrl;
}
@Override
public void run() {
String endpoint = RegionUtils.getCurrentRegion().getServiceEndpoints()
.get(ServiceAbbreviations.SQS);
String accountId = AwsToolkitCore.getDefault().getCurrentAccountId();
final IEditorInput input = new QueueEditorInput(queueUrl, endpoint, accountId);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
activeWindow.getActivePage().openEditor(input, "com.amazonaws.eclipse.explorer.sqs.queueEditor");
} catch (PartInitException e) {
AwsToolkitCore.getDefault().reportException("Unable to open the Amazon SQS queue editor", e);
}
}
});
}
}
| 7,824 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sqs/SQSContentProvider.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sqs;
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;
import com.amazonaws.services.sqs.AmazonSQS;
public class SQSContentProvider extends AbstractContentProvider {
public static class SQSRootElement {
public static final SQSRootElement ROOT_ELEMENT = new SQSRootElement();
}
public static class QueueNode extends ExplorerNode {
private final String queueUrl;
public QueueNode(String queueUrl) {
super(parseQueueName(queueUrl), 0,
loadImage(AwsToolkitCore.IMAGE_QUEUE),
new OpenQueueEditorAction(queueUrl));
this.queueUrl = queueUrl;
}
public String getQueueUrl() {
return queueUrl;
}
private static String parseQueueName(String queueUrl) {
int position = queueUrl.lastIndexOf('/');
if (position > 0) return queueUrl.substring(position + 1);
else return queueUrl;
}
}
@Override
public boolean hasChildren(Object element) {
return (element instanceof AWSResourcesRootElement ||
element instanceof SQSRootElement);
}
@Override
public Object[] loadChildren(Object parentElement) {
if ( parentElement instanceof AWSResourcesRootElement ) {
return new Object[] { SQSRootElement.ROOT_ELEMENT };
}
if (parentElement instanceof SQSRootElement) {
new DataLoaderThread(parentElement) {
@Override
public Object[] loadData() {
AmazonSQS sqs = AwsToolkitCore.getClientFactory().getSQSClient();
List<QueueNode> queueNodes = new ArrayList<>();
for (String queueUrl : sqs.listQueues().getQueueUrls()) {
queueNodes.add(new QueueNode(queueUrl));
}
return queueNodes.toArray();
}
}.start();
}
return Loading.LOADING;
}
@Override
public String getServiceAbbreviation() {
return ServiceAbbreviations.SQS;
}
}
| 7,825 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sqs/SQSActionProvider.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sqs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.navigator.CommonActionProvider;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.ContentProviderRegistry;
import com.amazonaws.eclipse.explorer.sqs.SQSContentProvider.QueueNode;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.DeleteQueueRequest;
import com.amazonaws.services.sqs.model.QueueAttributeName;
public class SQSActionProvider extends CommonActionProvider {
@Override
public void fillContextMenu(IMenuManager menu) {
StructuredSelection selection = (StructuredSelection)getActionSite().getStructuredViewer().getSelection();
menu.add(new CreateQueueAction());
boolean onlyQueuesSelected = true;
List<String> selectedQueues = new ArrayList<>();
Iterator<?> iterator = selection.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
if (next instanceof QueueNode) {
selectedQueues.add(((QueueNode)next).getQueueUrl());
} else {
onlyQueuesSelected = false;
}
}
if (selectedQueues.size() > 0 && onlyQueuesSelected) {
menu.add(new DeleteQueueAction(selectedQueues));
}
if (selectedQueues.size() == 1 && onlyQueuesSelected) {
menu.add(new Separator());
menu.add(new AddMessageAction(AwsToolkitCore.getClientFactory().getSQSClient(), selectedQueues.get(0), null));
}
}
private static class CreateQueueAction extends Action {
public CreateQueueAction() {
this.setText("Create New Queue");
this.setToolTipText("Create a new Amazon SQS Queue");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD));
}
@Override
public void run() {
AmazonSQS sqs = AwsToolkitCore.getClientFactory().getSQSClient();
CreateQueueDialog createQueueDialog = new CreateQueueDialog();
if (createQueueDialog.open() == 0) {
try {
Map<String, String> attributes = new HashMap<>();
if (createQueueDialog.getQueueDelay() > 0) {
attributes.put(QueueAttributeName.DelaySeconds.toString(), Integer.toString(createQueueDialog.getQueueDelay()));
}
sqs.createQueue(new CreateQueueRequest(createQueueDialog.getQueueName()).withAttributes(attributes));
ContentProviderRegistry.refreshAllContentProviders();
} catch (Exception e) {
AwsToolkitCore.getDefault().reportException("Unable to create SQS Queue", e);
}
}
}
}
private static class CreateQueueDialog extends MessageDialog {
private String queueName;
private int queueDelay = -1;
private Spinner queueDelaySpinner;
public CreateQueueDialog() {
super(Display.getDefault().getActiveShell(),
"Create New SQS Queue", null,
"Enter a name for your new SQS Queue, " +
"and an optional default message delay.",
MessageDialog.INFORMATION, new String[] {"OK", "Cancel"}, 0);
}
public String getQueueName() {
return queueName;
}
public int getQueueDelay() {
return queueDelay;
}
@Override
protected Control createCustomArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
composite.setLayout(new GridLayout(2, false));
new Label(composite, SWT.NONE).setText("Queue Name:");
final Text topicNameText = new Text(composite, SWT.BORDER);
topicNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
topicNameText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
queueName = topicNameText.getText();
updateControls();
}
});
new Label(composite, SWT.NONE).setText("Message Delay (seconds):");
queueDelaySpinner = new Spinner(composite, SWT.BORDER);
queueDelaySpinner.setMinimum(0);
queueDelaySpinner.setMaximum(50000);
queueDelaySpinner.setIncrement(1);
queueDelaySpinner.setSelection(0);
queueDelaySpinner.setPageIncrement(60);
queueDelaySpinner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
queueDelaySpinner.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
queueDelay = queueDelaySpinner.getSelection();
updateControls();
}
});
return composite;
}
private void updateControls() {
boolean queueDelayIsValid = true;
boolean queueNameIsValid = (queueName != null && queueName.trim().length() > 0);
boolean isValid = queueNameIsValid && queueDelayIsValid;
Button okButton = this.getButton(0);
if (okButton != null) okButton.setEnabled(isValid);
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
updateControls();
}
}
private static class DeleteQueueAction extends Action {
private final List<String> queues;
public DeleteQueueAction(List<String> queueUrls) {
this.queues = queueUrls;
this.setText("Delete Queue" + (queueUrls.size() > 1 ? "s" : ""));
this.setToolTipText("Delete the selected Amazon SQS queues");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE));
}
@Override
public void run() {
Dialog dialog = newConfirmationDialog("Delete selected queues?", "Are you sure you want to delete the selected Amazon SQS queues?");
if (dialog.open() != 0) return;
AmazonSQS sqs = AwsToolkitCore.getClientFactory().getSQSClient();
for (String queueUrl : queues) {
try {
sqs.deleteQueue(new DeleteQueueRequest(queueUrl));
} catch (Exception e) {
AwsToolkitCore.getDefault().reportException("Unable to delete Amazon SQS queue", e);
}
}
ContentProviderRegistry.refreshAllContentProviders();
}
private Dialog newConfirmationDialog(String title, String message) {
return new MessageDialog(Display.getDefault().getActiveShell(), title, null, message, MessageDialog.WARNING, new String[] {"OK", "Cancel"}, 0);
}
}
}
| 7,826 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sqs/AddMessageAction.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sqs;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.SendMessageRequest;
public class AddMessageAction extends Action {
private final AmazonSQS sqs;
private final String queueUrl;
private final IRefreshable refreshable;
public AddMessageAction(AmazonSQS sqs, String queueUrl, IRefreshable refreshable) {
this.sqs = sqs;
this.queueUrl = queueUrl;
this.refreshable = refreshable;
this.setText("Send Message");
this.setToolTipText("Sends a new message to this queue");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_PUBLISH));
}
@Override
public void run() {
AddMessageDialog addMessageDialog = new AddMessageDialog();
if (addMessageDialog.open() >= 0) {
SendMessageRequest sendMessageRequest = new SendMessageRequest(queueUrl, addMessageDialog.getMessage());
if (addMessageDialog.getDelay() > -1) {
sendMessageRequest.setDelaySeconds(addMessageDialog.getDelay());
}
sqs.sendMessage(sendMessageRequest);
if (refreshable != null) {
refreshable.refreshData();
}
}
}
private static class AddMessageDialog extends MessageDialog {
private Text text;
private String message;
private int messageDelay = -1;
private Spinner messageDelaySpinner;
public AddMessageDialog() {
super(Display.getDefault().getActiveShell(), "Send Message",
AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON),
"Enter your message:", 0, new String[] { "OK" }, 0);
}
@Override
protected Control createCustomArea(Composite parent) {
GridLayout parentGridLayout = new GridLayout();
parentGridLayout.verticalSpacing = 1;
parentGridLayout.marginHeight = 1;
parent.setLayout(parentGridLayout);
Composite composite = new Composite(parent, SWT.BORDER);
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
gridData.heightHint = 100;
gridData.widthHint = 400;
composite.setLayoutData(gridData);
composite.setLayout(new FillLayout());
text = new Text(composite, SWT.MULTI | SWT.BORDER);
Composite composite2 = new Composite(parent, SWT.NONE);
gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
gridData.widthHint = 400;
composite2.setLayoutData(gridData);
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.marginHeight = 1;
gridLayout.marginWidth = 0;
gridLayout.horizontalSpacing = 1;
composite2.setLayout(gridLayout);
final Button delayCheckButton = new Button(composite2, SWT.CHECK);
delayCheckButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (delayCheckButton.getSelection()) {
messageDelay = messageDelaySpinner.getSelection();
} else {
messageDelay = -1;
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
});
delayCheckButton.setSelection(false);
new Label(composite2, SWT.NONE).setText("Message Delay (seconds):");
messageDelaySpinner = new Spinner(composite2, SWT.BORDER);
messageDelaySpinner.setMinimum(0);
messageDelaySpinner.setMaximum(50000);
messageDelaySpinner.setIncrement(1);
messageDelaySpinner.setSelection(0);
messageDelaySpinner.setPageIncrement(60);
messageDelaySpinner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
messageDelaySpinner.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
delayCheckButton.setSelection(true);
messageDelay = messageDelaySpinner.getSelection();
}
});
messageDelaySpinner.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {}
@Override
public void focusGained(FocusEvent e) {
delayCheckButton.setSelection(true);
}
});
return parent;
}
@Override
public boolean close() {
message = text.getText();
return super.close();
}
public String getMessage() {
return message;
}
public int getDelay() {
return messageDelay;
}
}
}
| 7,827 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sqs/SQSLabelProvider.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.sqs;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider;
import com.amazonaws.eclipse.explorer.sqs.SQSContentProvider.SQSRootElement;
public class SQSLabelProvider extends ExplorerNodeLabelProvider {
@Override
public String getText(Object element) {
if (element instanceof SQSRootElement) return "Amazon SQS";
return getExplorerNodeText(element);
}
@Override
public Image getDefaultImage(Object element) {
if (element instanceof SQSRootElement) {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_SQS_SERVICE);
} else {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_QUEUE);
}
}
}
| 7,828 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/actions/ConfigurationActionProvider.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.actions;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.services.IDisposable;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.preferences.PreferenceConstants;
import com.amazonaws.eclipse.core.preferences.PreferencePropertyChangeListener;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.explorer.ContentProviderRegistry;
import com.amazonaws.eclipse.explorer.ExplorerNode;
/**
* Action provider for explorer toolbar and view menu.
*/
public class ConfigurationActionProvider extends CommonActionProvider {
private final RegionSelectionMenuAction regionSelectionAction;
private final RefreshAction refreshAction;
@Override
public void fillContextMenu(IMenuManager menu) {
StructuredSelection selection = (StructuredSelection)getActionSite().getStructuredViewer().getSelection();
if (selection.getFirstElement() instanceof ExplorerNode && selection.size() == 1) {
ExplorerNode node = (ExplorerNode)selection.getFirstElement();
if (node.getOpenAction() != null) {
menu.add(node.getOpenAction());
menu.add(new Separator());
}
}
}
private final class RefreshAction extends Action {
public RefreshAction() {
this.setText("Refresh");
this.setToolTipText("Refresh AWS Explorer");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH));
}
@Override
public void run() {
AwsToolkitCore.getDefault().getAccountManager().reloadAccountInfo();
ContentProviderRegistry.refreshAllContentProviders();
}
}
private final class RegionSelectionMenuAction extends Action implements IRefreshable, IDisposable {
private Menu menu;
private PreferencePropertyChangeListener regionChangeListener;
private RegionSelectionMenuAction() {
super(null, Action.AS_DROP_DOWN_MENU);
updateRegionFlag();
setId("aws-region-selection");
regionChangeListener = new PreferencePropertyChangeListener() {
@Override
public void watchedPropertyChanged() {
RegionSelectionMenuAction.this.refreshData();
}
};
AwsToolkitCore.getDefault().addDefaultRegionChangeListener(regionChangeListener);
}
@Override
public IMenuCreator getMenuCreator() {
return new IMenuCreator() {
@Override
public Menu getMenu(Menu parent) {
return null;
}
@Override
public Menu getMenu(Control parent) {
if (menu == null) menu = createMenu(parent);
return menu;
}
@Override
public void dispose() {
if (regionChangeListener != null) {
AwsToolkitCore.getDefault().removeDefaultRegionChangeListener(regionChangeListener);
}
if (menu != null) {
menu.dispose();
}
}
};
}
private Menu createMenu(final Control parent) {
Menu menu = new Menu(parent);
Region currentRegion = RegionUtils.getCurrentRegion();
for (final Region region : RegionUtils.getRegions()) {
MenuItem menuItem = new MenuItem(menu, SWT.RADIO);
menuItem.setText(region.getName());
menuItem.setData(region);
menuItem.setSelection(region.equals(currentRegion));
menuItem.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
IPreferenceStore preferenceStore = AwsToolkitCore.getDefault().getPreferenceStore();
preferenceStore.setValue(PreferenceConstants.P_DEFAULT_REGION, region.getId());
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
});
menuItem.setImage(lookupRegionFlag(region.getId()));
}
return menu;
}
private void updateRegionFlag() {
Region currentRegion = RegionUtils.getCurrentRegion();
setImageDescriptor(currentRegion.getFlagImageDescriptor());
if (menu != null) {
for (MenuItem menuItem : menu.getItems()) {
Region region = (Region)menuItem.getData();
menuItem.setSelection(region.equals(currentRegion));
}
}
}
private Image lookupRegionFlag(String regionId) {
Region r = RegionUtils.getRegion(regionId);
if (r != null)
return r.getFlagImage();
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON);
}
@Override
public void refreshData() {
updateRegionFlag();
}
@Override
public void dispose() {
if (regionChangeListener != null) {
AwsToolkitCore.getDefault().removeDefaultRegionChangeListener(regionChangeListener);
}
}
}
private final class AccountPreferencesAction extends Action {
public AccountPreferencesAction() {
setText("Configure AWS Accounts");
setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_GEAR));
}
@Override
public void run() {
String resource = AwsToolkitCore.ACCOUNT_PREFERENCE_PAGE_ID;
PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(
null, resource, new String[] { resource }, null);
dialog.open();
}
}
public ConfigurationActionProvider() {
regionSelectionAction = new RegionSelectionMenuAction();
refreshAction = new RefreshAction();
}
/**
* This method is invoked whenever the selection in the viewer changes, so
* we need to make sure not to add our action more than once.
*/
@Override
public void fillActionBars(IActionBars actionBars) {
for ( IContributionItem item : actionBars.getToolBarManager().getItems() ) {
if ( item.getId() == regionSelectionAction.getId() )
return;
}
actionBars.getToolBarManager().add(new Separator());
actionBars.getToolBarManager().add(refreshAction);
actionBars.getToolBarManager().add(new Separator());
actionBars.getToolBarManager().add(regionSelectionAction);
MenuManager menuMgr = new MenuManager("AWS Account", AwsToolkitCore.getDefault().getImageRegistry()
.getDescriptor(AwsToolkitCore.IMAGE_AWS_ICON), "");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
String currentAccountId = AwsToolkitCore.getDefault().getCurrentAccountId();
Map<String, String> accounts = AwsToolkitCore.getDefault().getAccountManager().getAllAccountNames();
for ( Entry<String, String> entry : accounts.entrySet() ) {
manager.add(
new SwitchAccountAction(entry.getKey(),
entry.getValue(),
currentAccountId.equals(entry.getKey())));
}
manager.add(new Separator());
manager.add(new AccountPreferencesAction());
}
});
actionBars.getMenuManager().add(menuMgr);
actionBars.getToolBarManager().update(true);
}
private final class SwitchAccountAction extends Action {
private final String accountId;
public SwitchAccountAction(String accountId, String accountName, boolean isCurrentAccount) {
super(accountName, IAction.AS_CHECK_BOX);
this.accountId = accountId;
setChecked(isCurrentAccount);
}
@Override
public void run() {
AwsToolkitCore.getDefault().getAccountManager().setDefaultAccountId(
RegionUtils.getCurrentRegion(),
accountId);
}
};
}
| 7,829 |
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/databinding/DecorationChangeListener.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.databinding;
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;
/**
* Simple listener that registers itself with an observable value that wraps an
* IStatus object, then shows or hides a specified control decoration and
* updates its description text when the wrapped IStatus object changes.
*/
public final class DecorationChangeListener implements IValueChangeListener {
private final ControlDecoration decoration;
public DecorationChangeListener(ControlDecoration decoration, IObservableValue observableValue) {
this.decoration = decoration;
observableValue.addValueChangeListener(this);
updateDecoration((IStatus)observableValue.getValue());
}
@Override
public void handleValueChange(ValueChangeEvent event) {
IStatus status = (IStatus)event.getObservableValue().getValue();
updateDecoration(status);
}
private void updateDecoration(IStatus status) {
if (status.isOK()) {
decoration.hide();
} else {
decoration.setDescriptionText(status.getMessage());
decoration.show();
}
}
}
| 7,830 |
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/databinding/ChainValidator.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.databinding;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.MultiValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
/**
* MultiValidator subclass that observes a value (and an optional enabler value
* that controls whether this validator should currently report errors or not),
* and runs a chain of IValidators on it. If any of the IValidators return an
* error status, this MultiValidator will immediately return that error status,
* otherwise this MultiValidator returns an OK status.
*
* @param <T>
* The type of the model object being observed.
*/
public class ChainValidator<T> extends MultiValidator {
private IObservableValue model;
private List<IValidator> validators = new ArrayList<>();
private final IObservableValue enabler;
public ChainValidator(IObservableValue model, IValidator... validators) {
this(model, null, validators);
}
public ChainValidator(IObservableValue model, IObservableValue enabler, IValidator... validators) {
this(model, enabler, Arrays.asList(validators));
}
public ChainValidator(IObservableValue model, IObservableValue enabler, List<IValidator> validators) {
this.model = model;
this.enabler = enabler;
this.validators = validators;
}
@Override
protected IStatus validate() {
@SuppressWarnings("unchecked")
T value = (T) model.getValue();
if (enabler != null) {
boolean isEnabled = enabler.getValue() != null && (Boolean) enabler.getValue();
if (!isEnabled) return ValidationStatus.ok();
}
for (IValidator validator : validators) {
IStatus status = validator.validate(value);
if (!status.isOK()) return status;
}
return ValidationStatus.ok();
}
}
| 7,831 |
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/databinding/NotInListValidator.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.databinding;
import org.eclipse.core.databinding.observable.set.IObservableSet;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
/**
* IValidator implementation that tests if the value being validated is included
* in the specified observable set. If it does exist in that observable set, a
* validation status is returned with the message specified in this object's
* constructor, otherwise if it does not exist in that observable set, then an
* OK status is returned.
*
* @param <T>
* The type of the object being validated.
*/
public class NotInListValidator<T> implements IValidator {
private IObservableSet observableSet;
private String message;
public NotInListValidator(IObservableSet observableSet, String message) {
this.observableSet = observableSet;
this.message = message;
}
@Override
public IStatus validate(Object object) {
@SuppressWarnings("unchecked")
T value = (T)object;
if (observableSet.contains(value)) return ValidationStatus.info(message);
return ValidationStatus.ok();
}
}
| 7,832 |
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/databinding/JsonStringValidator.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.databinding;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Simple IValidator implementation that returns an OK status if the String
* is in valid JSON format, otherwise it returns a validation status with
* the message specified in the constructor.
*/
public class JsonStringValidator implements IValidator {
private final String message;
private final boolean allowEmptyString;
private static final ObjectMapper mapper = new ObjectMapper();
public JsonStringValidator(String message, boolean allowEmptyString) {
this.message = message;
this.allowEmptyString = allowEmptyString;
}
@Override
public IStatus validate(Object value) {
String s = (String)value;
if (s == null || s.isEmpty()) {
return allowEmptyString ? ValidationStatus.ok() : ValidationStatus
.error(message);
}
try {
mapper.readTree(s);
} catch (Exception e) {
return ValidationStatus.error(message);
}
return ValidationStatus.ok();
}
}
| 7,833 |
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/databinding/BooleanValidator.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.databinding;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
/**
* Simple validator that checks a boolean value and returns an error message if
* it's false.
*/
public class BooleanValidator implements IValidator {
public String message;
public BooleanValidator(String message) {
this.message = message;
}
@Override
public IStatus validate(Object value) {
if ( !((Boolean) value) )
return ValidationStatus.error(message);
return ValidationStatus.ok();
}
}
| 7,834 |
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/databinding/IsFalseBooleanValidator.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.databinding;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
/**
* Simple validator that checks a boolean value is false and returns an error
* message if it's true.
*/
public class IsFalseBooleanValidator implements IValidator {
public String message;
public IsFalseBooleanValidator(String message) {
this.message = message;
}
@Override
public IStatus validate(Object value) {
if ( ((Boolean) value) )
return ValidationStatus.error(message);
return ValidationStatus.ok();
}
}
| 7,835 |
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/databinding/NotEmptyValidator.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.databinding;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
/**
* Simple IValidator implementation that returns an OK status if the String
* being validated is not empty, otherwise it returns a validation status with
* the message specified in the constructor.
*/
public class NotEmptyValidator implements IValidator {
public String message;
public NotEmptyValidator(String message) {
this.message = message;
}
@Override
public IStatus validate(Object value) {
String s = (String)value;
if (s == null || s.trim().length() == 0) return ValidationStatus.error(message);
return ValidationStatus.ok();
}
}
| 7,836 |
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/databinding/RangeValidator.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.databinding;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
/**
* Simple IValidator implementation that returns an OK status if the Long being
* validated is within the range, otherwise it returns a validation status with
* the message specified in the constructor.
*/
public class RangeValidator implements IValidator {
public String message;
public long minValue;
public long maxValue;
public RangeValidator(String message, long minValue, long maxValue) {
this.message = message;
this.minValue = minValue;
this.maxValue = maxValue;
}
@Override
public IStatus validate(Object value) {
Long s = (value instanceof String) ? Long.parseLong((String)value) : (Long) value;
if (s == null || s < minValue || s > maxValue)
return ValidationStatus.error(message);
return ValidationStatus.ok();
}
}
| 7,837 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/CodeStarUtils.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.eclipse.codestar.arn.ARN;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.services.codecommit.AWSCodeCommit;
import com.amazonaws.services.codecommit.model.GetRepositoryRequest;
import com.amazonaws.services.codecommit.model.RepositoryMetadata;
import com.amazonaws.services.codestar.AWSCodeStar;
import com.amazonaws.services.codestar.model.DescribeProjectRequest;
import com.amazonaws.services.codestar.model.DescribeProjectResult;
import com.amazonaws.services.codestar.model.ListProjectsRequest;
import com.amazonaws.services.codestar.model.ListResourcesRequest;
import com.amazonaws.services.codestar.model.ProjectSummary;
import com.amazonaws.services.codestar.model.Resource;
public class CodeStarUtils {
public static Map<String, DescribeProjectResult> getCodeStarProjects(String accountId, String regionId) {
Map<String, DescribeProjectResult> projectMap = new HashMap<>();
AWSCodeStar client = getCodeStarClient(accountId, regionId);
List<ProjectSummary> projectList = client.listProjects(new ListProjectsRequest()).getProjects();
for (ProjectSummary project : projectList) {
projectMap.put(project.getProjectId(),
client.describeProject(new DescribeProjectRequest().withId(project.getProjectId())));
}
return projectMap;
}
/*
* Get the AWS CodeCommit repositories associated with the given AWS CodeStar project.
*/
public static List<RepositoryMetadata> getCodeCommitRepositories(String accountId, String regionId, String codestarProjectId) {
AWSCodeStar codeStarClient = getCodeStarClient(accountId, regionId);
AWSCodeCommit codeCommitClient = getCodeCommitClient(accountId, regionId);
List<Resource> resources = codeStarClient.listResources(new ListResourcesRequest().withProjectId(codestarProjectId)).getResources();
List<String> codeCommitRepoNames = getCodeCommitRepoNames(resources);
List<RepositoryMetadata> repositoryMetadatas = new ArrayList<>();
for (String repoName : codeCommitRepoNames) {
repositoryMetadatas.add(codeCommitClient.getRepository(new GetRepositoryRequest()
.withRepositoryName(repoName)).getRepositoryMetadata());
}
return repositoryMetadatas;
}
/*
* Return a list of AWS CodeCommit repository names from a given list of AWS CodeStar resources
* that is associated with one AWS CodeStar project. Return an empty list if no AWS CodeCommit
* repository is found.
*/
private static List<String> getCodeCommitRepoNames(List<Resource> resources) {
List<String> repoNames = new ArrayList<>();
for (Resource resource : resources) {
ARN resourceArn = ARN.fromSafeString(resource.getId());
if ("codecommit".equals(resourceArn.getVendor())) {
repoNames.add(resourceArn.getRelativeId());
}
}
return repoNames;
}
public static AWSCodeStar getCodeStarClient(String accountId, String regionId) {
return AwsToolkitCore.getDefault().getClientFactory(accountId).getCodeStarClientByRegion(regionId);
}
public static AWSCodeCommit getCodeCommitClient(String accountId, String regionId) {
String endpoint = RegionUtils.getRegion(regionId).getServiceEndpoint(ServiceAbbreviations.CODECOMMIT);
return AwsToolkitCore.getDefault().getClientFactory(accountId).getCodeCommitClientByEndpoint(endpoint);
}
}
| 7,838 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/UIConstants.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar;
public class UIConstants {
public static final String CODESTAR_PROJECT_CHECKOUT_WIZARD_TITLE = "AWS CodeStar Project Checkout";
public static final String CODESTAR_PROJECT_CHECKOUT_WIZARD_SECTION = "AWSCodeStarProjectCheckoutWizard";
public static final String CODESTAR_PROJECT_CHECKOUT_PAGE_TITLE = "AWS CodeStar Project Selection";
public static final String CODESTAR_PROJECT_CHECKOUT_PAGE_DESCRIPTION = "Select the AWS CodeStar project you want to checkout from the remote host.";
}
| 7,839 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/CodeStarPlugin.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar;
import org.osgi.framework.BundleContext;
import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin;
/**
* The activator class controls the plug-in life cycle
*/
public class CodeStarPlugin extends AbstractAwsPlugin {
// The shared instance
private static CodeStarPlugin plugin;
/*
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static CodeStarPlugin getDefault() {
return plugin;
}
}
| 7,840 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/CodeStarAnalytics.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.ToolkitAnalyticsManager;
import com.amazonaws.eclipse.core.telemetry.ToolkitEvent.ToolkitEventBuilder;
public class CodeStarAnalytics {
private static final ToolkitAnalyticsManager ANALYTICS = AwsToolkitCore.getDefault().getAnalyticsManager();
// Import AWS CodeStar Project
private static final String EVENT_IMPORT_PROJECT = "codestar_importProject";
// Attribute
private static final String ATTR_NAME_END_RESULT = "result";
public static void trackImportProject(EventResult result) {
publishEventWithAttributes(EVENT_IMPORT_PROJECT, ATTR_NAME_END_RESULT, result.getResultText());
}
private static void publishEventWithAttributes(String eventType, String... attributes) {
ToolkitEventBuilder builder = ANALYTICS.eventBuilder().setEventType(eventType);
for (int i = 0; i < attributes.length; i += 2) {
builder.addAttribute(attributes[i], attributes[i + 1]);
}
ANALYTICS.publishEvent(builder.build());
}
public static enum EventResult {
SUCCEEDED("Succeeded"),
FAILED("Failed"),
CANCELED("Canceled")
;
private final String resultText;
private EventResult(String resultText) {
this.resultText = resultText;
}
public String getResultText() {
return resultText;
}
}
}
| 7,841 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/handler/CodeStarProjectCheckoutHandler.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar.handler;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.codestar.wizard.CodeStarProjectCheckoutWizard;
public class CodeStarProjectCheckoutHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
CodeStarProjectCheckoutWizard newWizard = new CodeStarProjectCheckoutWizard();
newWizard.init(PlatformUI.getWorkbench(), null);
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard);
return dialog.open();
}
}
| 7,842 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/page/CodeStarProjectCheckoutPage.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar.page;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCombo;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLabel;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import com.amazonaws.eclipse.codecommit.credentials.GitCredential;
import com.amazonaws.eclipse.codecommit.credentials.GitCredentialsManager;
import com.amazonaws.eclipse.codecommit.widgets.GitCredentialsComposite;
import com.amazonaws.eclipse.codestar.CodeStarPlugin;
import com.amazonaws.eclipse.codestar.CodeStarUtils;
import com.amazonaws.eclipse.codestar.UIConstants;
import com.amazonaws.eclipse.codestar.model.CodeStarProjectCheckoutWizardDataModel;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.core.ui.AccountSelectionComposite;
import com.amazonaws.eclipse.core.ui.RegionSelectionComposite;
import com.amazonaws.services.codecommit.model.RepositoryMetadata;
import com.amazonaws.services.codestar.model.DescribeProjectResult;
/**
* The wizard page used to identify CodeStar project to be imported.
*/
public class CodeStarProjectCheckoutPage extends WizardPage {
private final CodeStarProjectCheckoutWizardDataModel dataModel;
private final DataBindingContext dataBindingContext;
private final AggregateValidationStatus aggregateValidationStatus;
private static final String[] CODESTAR_PROJECT_TABLE_TITLE = {"Project Name", "Project ID", "Project Description"};
private AccountSelectionComposite accountSelectionComposite;
private RegionSelectionComposite regionSelectionComposite;
private Table codeStarProjectTable;
private Combo repositoryCombo;
private GitCredentialsComposite gitCredentialsComposite;
private final Map<String, GitCredential> gitCredentials = GitCredentialsManager.getGitCredentials();
public CodeStarProjectCheckoutPage(final CodeStarProjectCheckoutWizardDataModel dataModel) {
super(CodeStarProjectCheckoutPage.class.getName());
setTitle(UIConstants.CODESTAR_PROJECT_CHECKOUT_PAGE_TITLE);
setDescription(UIConstants.CODESTAR_PROJECT_CHECKOUT_PAGE_DESCRIPTION);
this.dataModel = dataModel;
this.dataBindingContext = new DataBindingContext();
this.aggregateValidationStatus = new AggregateValidationStatus(
dataBindingContext, AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent arg0) {
populateValidationStatus();
}
});
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
createAccountAndRegionSelectionComposite(composite);
createProjectSectionComposite(composite);
createGitCredentialsComposite(composite);
initDefaults();
setControl(composite);
}
private void initDefaults() {
if (!AwsToolkitCore.getDefault().getAccountManager().validAccountsConfigured()) return;
accountSelectionComposite.selectAccountId(AwsToolkitCore.getDefault().getCurrentAccountId());
regionSelectionComposite.setSelection(0);
dataModel.setAccountId(accountSelectionComposite.getSelectedAccountId());
dataModel.setProjectRegionId(regionSelectionComposite.getSelectedRegion());
onAccountOrRegionSelectionChange();
}
/*
* Initialize account selection UI and set accountId in the model.
*/
private void createAccountAndRegionSelectionComposite(Composite parent) {
Group accountGroup = newGroup(parent, "Select AWS account and region:");
accountGroup.setLayout(new GridLayout(1, false));
accountSelectionComposite = new AccountSelectionComposite(accountGroup, SWT.None);
accountSelectionComposite.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
dataModel.setAccountId(accountSelectionComposite.getSelectedAccountId());
onAccountOrRegionSelectionChange();
}
});
regionSelectionComposite = new RegionSelectionComposite(accountGroup, SWT.None, ServiceAbbreviations.CODESTAR);
regionSelectionComposite.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
dataModel.setProjectRegionId(regionSelectionComposite.getSelectedRegion());
onAccountOrRegionSelectionChange();
}
});
}
private void createProjectSectionComposite(Composite composite) {
Group projectGroup = newGroup(composite, "Select AWS CodeStar project and repository:");
projectGroup.setLayout(new GridLayout(2, false));
codeStarProjectTable = newTable(projectGroup, 2, CODESTAR_PROJECT_TABLE_TITLE);
codeStarProjectTable.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onCodeStarProjectTableSelection();
}
});
newLabel(projectGroup, "Select repository: ", 1);
repositoryCombo = newCombo(projectGroup, 1);
repositoryCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onRepositoryComboSelection();
}
});
}
private void createGitCredentialsComposite(Composite composite) {
Group gitCredentialsGroup = newGroup(composite, "Configure Git credentials:");
gitCredentialsGroup.setLayout(new GridLayout(1, false));
this.gitCredentialsComposite = new GitCredentialsComposite(
gitCredentialsGroup, dataBindingContext, dataModel.getGitCredentialsDataModel());
}
private void onCodeStarProjectTableSelection() {
try {
DescribeProjectResult selection = (DescribeProjectResult)codeStarProjectTable.getItem(codeStarProjectTable.getSelectionIndex()).getData();
dataModel.setProjectName(selection.getName());
dataModel.setProjectId(selection.getId());
List<RepositoryMetadata> repositories = getCodeCommitRepositories();
repositoryCombo.removeAll();
for (RepositoryMetadata metadata : repositories) {
repositoryCombo.add(metadata.getRepositoryName());
repositoryCombo.setData(metadata.getRepositoryName(), metadata);
}
if (!repositories.isEmpty()) {
repositoryCombo.select(0);
onRepositoryComboSelection();
} else {
CodeStarPlugin.getDefault().logWarning("No CodeCommit repository found for this project.", null);
}
} catch (Exception e) {
CodeStarPlugin.getDefault().reportException(e.getMessage(), e);
}
}
// dataModel.projectId must be specified before this call.
private void onRepositoryComboSelection() {
try {
String selectedRepo = repositoryCombo.getItem(repositoryCombo.getSelectionIndex());
RepositoryMetadata metadata = (RepositoryMetadata)repositoryCombo.getData(selectedRepo);
dataModel.setRepoHttpUrl(metadata.getCloneUrlHttp());
dataModel.setRepoName(metadata.getRepositoryName());
populateValidationStatus();
} catch (Exception e) {
CodeStarPlugin.getDefault().reportException(e.getMessage(), e);
}
}
private Table newTable(Composite composite, int colspan, String[] headers) {
Table table = new Table(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL);
table.setLinesVisible(true);
table.setHeaderVisible(true);
int columnWeight = 100 / headers.length;
TableLayout layout = new TableLayout();
for (int i = 0; i < headers.length; ++i) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(headers[i]);
layout.addColumnData(new ColumnWeightData(columnWeight));
}
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.heightHint = 100;
data.widthHint = 200;
data.horizontalSpan = colspan;
table.setLayoutData(data);
table.setLayout(layout);
return table;
}
private void onAccountOrRegionSelectionChange() {
try {
populateCodeStarProjectUI();
} catch (Exception e) {
CodeStarPlugin.getDefault().reportException(e.getMessage(), e);
}
}
private void populateCodeStarProjectUI() {
populateGitCredentialsComposite();
populateValidationStatus();
codeStarProjectTable.removeAll();
repositoryCombo.removeAll();
for (Entry<String, DescribeProjectResult> project : getCodeStarProjects().entrySet()) {
TableItem item = new TableItem(codeStarProjectTable, SWT.LEFT);
item.setText(getTableItem(project.getValue()));
item.setData(project.getValue());
}
dataModel.setProjectName(null);
dataModel.setRepoHttpUrl(null);
dataModel.setRepoName(null);
}
private void populateGitCredentialsComposite() {
Map<String, String> accounts = AwsToolkitCore.getDefault().getAccountManager().getAllAccountNames();
String profileName = accounts.get(dataModel.getAccountId());
GitCredential selectedGitCredential = gitCredentials.get(profileName);
if (selectedGitCredential != null) {
gitCredentialsComposite.populateGitCredential(
selectedGitCredential.getUsername(), selectedGitCredential.getPassword());
} else {
gitCredentialsComposite.populateGitCredential(
"", "");
}
dataModel.getGitCredentialsDataModel().setUserAccount(dataModel.getAccountId());
dataModel.getGitCredentialsDataModel().setRegionId(dataModel.getProjectRegionId());
}
private Map<String, DescribeProjectResult> getCodeStarProjects() {
return CodeStarUtils.getCodeStarProjects(dataModel.getAccountId(), dataModel.getProjectRegionId());
}
private List<RepositoryMetadata> getCodeCommitRepositories() {
return CodeStarUtils.getCodeCommitRepositories(
dataModel.getAccountId(), dataModel.getProjectRegionId(), dataModel.getProjectId());
}
private String[] getTableItem(DescribeProjectResult project) {
return new String[]{project.getName(), project.getId(), project.getDescription()};
}
private void populateValidationStatus() {
if (!nonBindingDataModelStatusOk()) {
super.setPageComplete(false);
return;
}
IStatus status = getValidationStatus();
if (status == null || status.getSeverity() == IStatus.OK) {
setErrorMessage(null);
super.setPageComplete(true);
} else {
setErrorMessage(status.getMessage());
super.setPageComplete(false);
}
}
private boolean nonBindingDataModelStatusOk() {
return dataModel.getAccountId() != null &&
dataModel.getProjectId() != null &&
dataModel.getProjectName() != null &&
dataModel.getProjectRegionId() != null &&
dataModel.getRepoHttpUrl() != null &&
dataModel.getRepoName() != null;
}
private IStatus getValidationStatus() {
if (aggregateValidationStatus == null) return null;
Object value = aggregateValidationStatus.getValue();
if (!(value instanceof IStatus)) return null;
return (IStatus)value;
}
}
| 7,843 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/arn/ARNSyntaxException.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar.arn;
public class ARNSyntaxException extends Exception {
private static final long serialVersionUID = -6197308298174187307L;
private String input;
public ARNSyntaxException(String input, String reason) {
super(reason);
if (input == null || reason == null) {
throw new NullPointerException();
}
this.input = input;
}
public String getInput() {
return input;
}
public String getReason() {
return super.getMessage();
}
@Override
public String getMessage() {
StringBuffer sb = new StringBuffer();
sb.append(getReason());
sb.append(": ");
sb.append(input);
return sb.toString();
}
} | 7,844 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/arn/ARN.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar.arn;
import com.amazonaws.util.StringUtils;
public class ARN {
// An ARN's utf8 representation takes at most 1600 bytes.
public static final int MAX_BYTES = 1600;
private final String vendor;
private final String region;
private final String namespace;
private final String relativeId;
private final String partition;
/**
* Constructs an ARN with vendor, region, namespace, and relativeId. All except region and namespace must be non-null. If
* region is null it will be converted to the empty string. May throw an ARNSyntaxException if the resulting
* stringified ARN will have a UTF8 representation longer than MAX_BYTES.
*/
private ARN(String partition, String vendor, String region, String namespace, String relativeId) throws ARNSyntaxException {
if (vendor == null || relativeId == null || partition == null) {
throw new NullPointerException();
}
this.vendor = vendor;
this.relativeId = relativeId;
this.partition = partition;
if (region == null) {
this.region = "";
} else {
this.region = region;
}
if (namespace == null) {
this.namespace = "";
} else {
this.namespace = namespace;
}
}
/**
* Returns an ARN parsed from arnString. Throws ARNSyntaxException if things look bad. A valid ARN could look like this:
* <b>arn:aws:codecommit:us-west-2:012345678901:resource-id</b>, and it could be parsed as:
* <p><ul>
* <li>partition: aws
* <li>vendor: codecommit
* <li>region: us-west-2
* <li>namespace: 012345678901
* <li>relativeId: resource-id
* </ul></p>
*
* @param arnString
* @throws ARNSyntaxException
*/
public static ARN fromString(String arnString) throws ARNSyntaxException {
if (StringUtils.isNullOrEmpty(arnString)) {
throw new IllegalArgumentException("The provided ARN is null or empty!");
}
// If the ultimate ARN is going to be too long, fail early.
validateARNLength(arnString);
String prefix = "arn:";
if (!arnString.startsWith(prefix)) {
throw new ARNSyntaxException(arnString, "ARNs must start with '" + prefix + "'");
}
//Partition
int oldIndex = prefix.length();
int newIndex = arnString.indexOf(':', oldIndex);
if (newIndex < 0) {
throw new ARNSyntaxException(arnString, "Second colon parition not found");
}
if (newIndex == oldIndex) {
throw new ARNSyntaxException(arnString, "Partition must be non-empty");
}
String partition = arnString.substring(oldIndex, newIndex);
//Vendor
oldIndex = newIndex + 1;
newIndex = arnString.indexOf(':', oldIndex);
if (newIndex < 0) {
throw new ARNSyntaxException(arnString, "Third colon vendor not found");
}
if(newIndex == oldIndex) {
throw new ARNSyntaxException(arnString, "Vendor must be non-empty");
}
String vendor = arnString.substring(oldIndex, newIndex);
// Region
oldIndex = newIndex + 1;
newIndex = arnString.indexOf(':', oldIndex);
if (newIndex < 0) {
throw new ARNSyntaxException(arnString, "Fourth colon (region/namespace delimiter) not found");
}
String region = arnString.substring(oldIndex, newIndex);
// Namespace
oldIndex = newIndex + 1;
newIndex = arnString.indexOf(':', oldIndex);
if (newIndex < 0) {
throw new ARNSyntaxException(arnString, "Fifth colon (namespace/relative-id delimiter) not found");
}
String namespace = arnString.substring(oldIndex, newIndex);
// Relative Id
String relativeId = arnString.substring(newIndex + 1);
if (relativeId.length() == 0) {
throw new ARNSyntaxException(arnString, "The Relative Id must be non-empty");
}
return new ARN(partition, vendor, region, namespace, relativeId);
}
/**
* Returns an ARN parsed from arnString. Assumes that the string is well-formed. If it's
* not a RuntimeException will be thrown.
* @param arnString
*/
public static ARN fromSafeString(String arnString) {
try {
return fromString(arnString);
} catch (ARNSyntaxException e) {
throw new RuntimeException("Caught unexpected syntax violation. Consider using ARN.fromString().", e);
}
}
/**
* Returns the ARN's vendor
*/
public String getVendor() {
return vendor;
}
/**
* Returns the ARN's region. May be the empty string if the ARN is
* regionless.
*/
public String getRegion() {
return region;
}
/**
* Returns the ARN's namespace
*/
public String getNamespace() {
return namespace;
}
/**
* Returns the ARN's relative id
*/
public String getRelativeId() {
return relativeId;
}
/**
* Returns the ARN's partition
*/
public String getPartition() {
return partition;
}
/**
* Throws ARNSyntaxException if arnString is more than MAX_BYTES in its UTF-8 representation
* @param arnString
* @throws ARNSyntaxException
*/
private static void validateARNLength(String arnString) throws ARNSyntaxException {
byte[] bytes = arnString.getBytes(StringUtils.UTF8);
if (bytes.length > MAX_BYTES) {
throw new ARNSyntaxException(arnString, "ARNs must be at most " + MAX_BYTES);
}
}
} | 7,845 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/wizard/CodeStarProjectCheckoutWizard.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar.wizard;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.egit.core.securestorage.UserPasswordCredentials;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.ui.IImportWizard;
import org.eclipse.ui.IWorkbench;
import com.amazonaws.eclipse.codecommit.credentials.GitCredential;
import com.amazonaws.eclipse.codecommit.credentials.GitCredentialsManager;
import com.amazonaws.eclipse.codestar.CodeStarAnalytics;
import com.amazonaws.eclipse.codestar.CodeStarPlugin;
import com.amazonaws.eclipse.codestar.UIConstants;
import com.amazonaws.eclipse.codestar.CodeStarAnalytics.EventResult;
import com.amazonaws.eclipse.codestar.model.CodeStarProjectCheckoutWizardDataModel;
import com.amazonaws.eclipse.codestar.page.CodeStarProjectCheckoutPage;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.egit.GitRepositoryInfo;
import com.amazonaws.eclipse.core.egit.RepositorySelection;
import com.amazonaws.eclipse.core.egit.UIText;
import com.amazonaws.eclipse.core.egit.jobs.CloneGitRepositoryJob;
import com.amazonaws.eclipse.core.egit.jobs.ImportProjectJob;
import com.amazonaws.eclipse.core.egit.ui.CloneDestinationPage;
import com.amazonaws.eclipse.core.egit.ui.SourceBranchPage;
import com.amazonaws.eclipse.core.util.WorkbenchUtils;
/**
* Wizard for importing an existing CodeStar project.
*/
@SuppressWarnings({ "restriction" })
public class CodeStarProjectCheckoutWizard extends Wizard implements IImportWizard {
protected IWorkbench workbench;
protected CodeStarProjectCheckoutWizardDataModel dataModel;
// a page for CodeStar project selection
protected CodeStarProjectCheckoutPage checkoutPage;
// a page for repository branch selection
protected SourceBranchPage sourceBranchPage;
// a page for selection of the clone destination
protected CloneDestinationPage cloneDestinationPage;
/**
* the current selected repository info.
*/
private volatile GitRepositoryInfo currentGitRepositoryInfo;
/**
* Construct CodeStarProjectCheckoutWizard by not providing a data model will
* open up the CodeStarProjectCheckoutPage.
*/
public CodeStarProjectCheckoutWizard() {
super();
setWindowTitle(UIConstants.CODESTAR_PROJECT_CHECKOUT_WIZARD_TITLE);
setDefaultPageImageDescriptor(
AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO));
setNeedsProgressMonitor(true);
dataModel = new CodeStarProjectCheckoutWizardDataModel();
checkoutPage = new CodeStarProjectCheckoutPage(this.dataModel);
sourceBranchPage = createSourceBranchPage();
cloneDestinationPage = createCloneDestinationPage();
}
@Override
public void init(IWorkbench workbench, IStructuredSelection arg1) {
this.workbench = workbench;
}
@Override
final public void addPages() {
addPage(checkoutPage);
addPage(sourceBranchPage);
addPage(cloneDestinationPage);
}
@Override
public boolean performFinish() {
try {
final File destinationFile = cloneDestinationPage.getDestinationFile();
getContainer().run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
monitor.subTask("Cloning repository...");
try {
new CloneGitRepositoryJob(CodeStarProjectCheckoutWizard.this, sourceBranchPage, cloneDestinationPage, getGitRepositoryInfo())
.execute(monitor);
} catch (URISyntaxException e) {
throw new InvocationTargetException(e);
}
GitCredentialsManager.getGitCredentials().put(
AwsToolkitCore.getDefault().getAccountManager()
.getAllAccountNames()
.get(dataModel.getAccountId()),
new GitCredential(
dataModel.getGitCredentialsDataModel()
.getUsername(), dataModel
.getGitCredentialsDataModel()
.getPassword()));
monitor.subTask("Importing project...");
IFile fileToOpen = new ImportProjectJob(dataModel.getProjectId(), destinationFile)
.execute(monitor);
if (fileToOpen != null) {
WorkbenchUtils.selectAndReveal(fileToOpen, workbench); // show in explorer
WorkbenchUtils.openFileInEditor(fileToOpen, workbench); // show in editor
}
monitor.done();
}
});
} catch (InvocationTargetException e) {
CodeStarAnalytics.trackImportProject(EventResult.FAILED);
CodeStarPlugin.getDefault().reportException(e.getMessage(), e);
return false;
} catch (InterruptedException e) {
CodeStarAnalytics.trackImportProject(EventResult.CANCELED);
CodeStarPlugin.getDefault().reportException(
UIText.GitCreateProjectViaWizardWizard_AbortedMessage, e);
return false;
}
CodeStarAnalytics.trackImportProject(EventResult.SUCCEEDED);
return true;
}
@Override
public boolean performCancel() {
CodeStarAnalytics.trackImportProject(EventResult.CANCELED);
return super.performCancel();
}
private SourceBranchPage createSourceBranchPage() {
return new SourceBranchPage() {
@Override
public void setVisible(boolean visible) {
if (visible) {
setSelection(getRepositorySelection());
setCredentials(getCredentials());
}
super.setVisible(visible);
}
};
}
private CloneDestinationPage createCloneDestinationPage() {
return new CloneDestinationPage() {
@Override
public void setVisible(boolean visible) {
if (visible)
setSelection(getRepositorySelection(),
sourceBranchPage.getAvailableBranches(),
sourceBranchPage.getSelectedBranches(),
sourceBranchPage.getHEAD());
super.setVisible(visible);
}
};
}
/**
* @return the repository specified in the data model.
*/
private RepositorySelection getRepositorySelection() {
try {
return new RepositorySelection(new URIish(
dataModel.getRepoHttpUrl()), null);
} catch (URISyntaxException e) {
CodeStarPlugin.getDefault().reportException(
UIText.GitImportWizard_errorParsingURI, e);
return null;
} catch (Exception e) {
CodeStarPlugin.getDefault().reportException(e.getMessage(), e);
return null;
}
}
/**
* @return the credentials
*/
protected UserPasswordCredentials getCredentials() {
try {
return getGitRepositoryInfo().getCredentials();
} catch (Exception e) {
CodeStarPlugin.getDefault().reportException(e.getMessage(), e);
return null;
}
}
/**
* currentGitRepositoryInfo should be updated along with the data model.
*
* @return The GitRepositoryInfo that is being currently working in.
* @throws URISyntaxException
*/
public GitRepositoryInfo getGitRepositoryInfo() throws URISyntaxException {
if (currentGitRepositoryInfo == null
|| !dataModel.getRepoHttpUrl().equals(
currentGitRepositoryInfo.getCloneUri())) {
currentGitRepositoryInfo = new GitRepositoryInfo(
dataModel.getRepoHttpUrl());
currentGitRepositoryInfo.setRepositoryName(dataModel.getRepoName());
}
currentGitRepositoryInfo.setShouldSaveCredentialsInSecureStore(true);
currentGitRepositoryInfo.setCredentials(dataModel
.getGitCredentialsDataModel().getUsername(), dataModel
.getGitCredentialsDataModel().getPassword());
return currentGitRepositoryInfo;
}
}
| 7,846 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codestar/src/com/amazonaws/eclipse/codestar/model/CodeStarProjectCheckoutWizardDataModel.java | /*
* Copyright 2011-2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.codestar.model;
import com.amazonaws.eclipse.core.model.GitCredentialsDataModel;
public class CodeStarProjectCheckoutWizardDataModel {
private String accountId;
private String projectName;
private String projectId;
private String projectRegionId;
private String repoName;
private String repoHttpUrl;
private final GitCredentialsDataModel gitCredentialsDataModel = new GitCredentialsDataModel();
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getProjectRegionId() {
return projectRegionId;
}
public void setProjectRegionId(String projectRegionId) {
this.projectRegionId = projectRegionId;
}
public String getRepoName() {
return repoName;
}
public void setRepoName(String RepoName) {
this.repoName = RepoName;
}
public String getRepoHttpUrl() {
return repoHttpUrl;
}
public void setRepoHttpUrl(String repoHttpUrl) {
this.repoHttpUrl = repoHttpUrl;
}
public GitCredentialsDataModel getGitCredentialsDataModel() {
return gitCredentialsDataModel;
}
}
| 7,847 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/EnvVarNameValidator.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.explorer.lambda;
import java.util.regex.Pattern;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
public class EnvVarNameValidator implements IValidator {
private static final Pattern PATTERN = Pattern.compile("^[a-zA-Z]\\w*");
/* (non-Javadoc)
* @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
*/
@Override
public IStatus validate(Object value) {
String name = (String) value;
if (PATTERN.matcher(name).matches()) {
return ValidationStatus.ok();
}
return ValidationStatus.error("Key must start with a letter and only contain letters, numbers, and underscores.");
}
}
| 7,848 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/LambdaLabelProvider.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.explorer.lambda;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider;
import com.amazonaws.eclipse.explorer.lambda.LambdaContentProvider.LambdaRootElement;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
public class LambdaLabelProvider extends ExplorerNodeLabelProvider {
@Override
public String getText(Object element) {
if (element instanceof LambdaRootElement) return "AWS Lambda";
return getExplorerNodeText(element);
}
@Override
public Image getDefaultImage(Object element) {
if (element instanceof LambdaRootElement) {
return LambdaPlugin.getDefault().getImageRegistry().get(LambdaPlugin.IMAGE_LAMBDA);
} else {
return LambdaPlugin.getDefault().getImageRegistry().get(LambdaPlugin.IMAGE_FUNCTION);
}
}
}
| 7,849 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionEnvVarsTable.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.explorer.lambda;
import java.util.ArrayList;
import java.util.HashMap;
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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.model.KeyValueSetDataModel;
import com.amazonaws.eclipse.core.model.KeyValueSetDataModel.Pair;
import com.amazonaws.eclipse.core.ui.KeyValueSetEditingComposite;
import com.amazonaws.eclipse.core.ui.KeyValueSetEditingComposite.KeyValueEditingUiText;
import com.amazonaws.eclipse.core.ui.KeyValueSetEditingComposite.KeyValueSetEditingCompositeBuilder;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.model.AWSLambdaException;
import com.amazonaws.services.lambda.model.Environment;
import com.amazonaws.services.lambda.model.EnvironmentResponse;
import com.amazonaws.services.lambda.model.GetFunctionConfigurationRequest;
import com.amazonaws.services.lambda.model.UpdateFunctionConfigurationRequest;
public class FunctionEnvVarsTable extends Composite {
private final FunctionEditorInput functionEditorInput;
private final KeyValueSetEditingComposite envVarsEditingComposite;
private final KeyValueSetDataModel envVarsDataModel;
public FunctionEnvVarsTable(Composite parent, FormToolkit toolkit, FunctionEditorInput functionEditorInput) {
super(parent, SWT.NONE);
this.functionEditorInput = functionEditorInput;
this.setLayout(new GridLayout());
this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
envVarsDataModel = new KeyValueSetDataModel(-1, new ArrayList<Pair>());
envVarsEditingComposite = new KeyValueSetEditingCompositeBuilder()
.saveListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onSaveEnvVars();
}
})
.addKeyValidator(new EnvVarNameValidator())
.uiText(new KeyValueEditingUiText(
"Add Environment Variable",
"Add a new Environment Variable",
"Edit Environment Variable",
"Edit the existing Environment Variable",
"Key:",
"Value:"))
.build(this, envVarsDataModel);
Composite buttonComposite = new Composite(this, SWT.NONE);
buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
buttonComposite.setLayout(new GridLayout(1, false));
refresh();
}
public void refresh() {
envVarsDataModel.getPairSet().clear();
EnvironmentResponse environment = functionEditorInput.getLambdaClient()
.getFunctionConfiguration(new GetFunctionConfigurationRequest()
.withFunctionName(functionEditorInput.getFunctionName()))
.getEnvironment();
if (environment != null && environment.getVariables() != null) {
Map<String, String> envVarsMap = environment.getVariables();
for (Entry<String, String> entry : envVarsMap.entrySet()) {
envVarsDataModel.getPairSet().add(new Pair(entry.getKey(), entry.getValue()));
}
}
envVarsEditingComposite.refresh();
}
private void onSaveEnvVars() {
try {
AWSLambda lambda = functionEditorInput.getLambdaClient();
Map<String, String> envVarsMap = new HashMap<>();
for (Pair pair : envVarsDataModel.getPairSet()) {
envVarsMap.put(pair.getKey(), pair.getValue());
}
lambda.updateFunctionConfiguration(new UpdateFunctionConfigurationRequest()
.withFunctionName(functionEditorInput.getFunctionName())
.withEnvironment(new Environment()
.withVariables(envVarsMap)));
} catch (AWSLambdaException e) {
LambdaPlugin.getDefault().reportException(e.getMessage(), e);
}
}
}
| 7,850 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/LambdaActionProvider.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.explorer.lambda;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.navigator.CommonActionProvider;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.DeleteResourceConfirmationDialog;
import com.amazonaws.eclipse.explorer.ContentProviderRegistry;
import com.amazonaws.eclipse.explorer.lambda.LambdaContentProvider.FunctionNode;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.project.wizard.NewLambdaJavaFunctionProjectWizard;
import com.amazonaws.eclipse.lambda.project.wizard.NewServerlessProjectWizard;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.model.AWSLambdaException;
import com.amazonaws.services.lambda.model.DeleteFunctionRequest;
public class LambdaActionProvider 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;
}
menu.add(new CreateLambdaProjectAction());
menu.add(new CreateServerlessProjectAction());
Object firstElement = selection.getFirstElement();
if ( firstElement instanceof FunctionNode ) {
menu.add(new DeleteFunctionAction((FunctionNode) firstElement));
}
}
private final class CreateLambdaProjectAction extends Action {
public CreateLambdaProjectAction() {
this.setText("Create a Lambda Project");
this.setDescription("Create a new Lambda project in your current workspace, this does not upload to AWS Lambda.");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD));
}
@Override
public void run() {
NewLambdaJavaFunctionProjectWizard newWizard = new NewLambdaJavaFunctionProjectWizard();
newWizard.init(PlatformUI.getWorkbench(), null);
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard);
dialog.open();
}
}
private final class CreateServerlessProjectAction extends Action {
public CreateServerlessProjectAction() {
this.setText("Create a Serverless Project");
this.setDescription("Create a new Serverless project in your current workspace, this does not deploy to Amazon CloudFormation.");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD));
}
@Override
public void run() {
NewServerlessProjectWizard newWizard = new NewServerlessProjectWizard();
newWizard.init(PlatformUI.getWorkbench(), null);
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard);
dialog.open();
}
}
private final class DeleteFunctionAction extends Action {
private final FunctionNode function;
public DeleteFunctionAction(FunctionNode function) {
this.function = function;
this.setText("Delete Function");
this.setDescription("Deleting this Lambda function will permanently remove the associated code. The associated event source mappings will also be removed, but the logs and role will not be deleted.");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE));
}
@Override
public void run() {
Dialog dialog = new DeleteResourceConfirmationDialog(Display.getDefault().getActiveShell(),
function.getName(), "function");
if (dialog.open() != Window.OK) {
return;
}
Job deleteStackJob = new Job("Deleting Function...") {
@Override
protected IStatus run(IProgressMonitor monitor) {
AWSLambda lambda = AwsToolkitCore.getClientFactory().getLambdaClient();
IStatus status = Status.OK_STATUS;
try {
lambda.deleteFunction(new DeleteFunctionRequest()
.withFunctionName(function.getName()));
} catch (AWSLambdaException e) {
status = new Status(IStatus.ERROR, LambdaPlugin.getDefault().getPluginId(), e.getMessage(), e);
}
ContentProviderRegistry.refreshAllContentProviders();
return status;
}
};
deleteStackJob.schedule();
}
}
}
| 7,851 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionEditorInput.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.explorer.lambda;
import org.eclipse.jface.resource.ImageDescriptor;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.services.lambda.AWSLambda;
public class FunctionEditorInput extends AbstractAwsResourceEditorInput {
private final String functionArn;
private final String functionName;
public FunctionEditorInput(String accountId, String regionId, String functionArn, String functionName) {
super(RegionUtils.getRegion(regionId).getServiceEndpoint(ServiceAbbreviations.LAMBDA), accountId, regionId);
this.functionArn = functionArn;
this.functionName = functionName;
}
public String getFunctionArn() {
return functionArn;
}
public String getFunctionName() {
return functionName;
}
@Override
public ImageDescriptor getImageDescriptor() {
return LambdaPlugin.getDefault().getImageRegistry().getDescriptor(LambdaPlugin.IMAGE_FUNCTION);
}
@Override
public String getName() {
return functionName;
}
@Override
public String getToolTipText() {
return "AWS Lambda Function Editor - " + getName();
}
public AWSLambda getLambdaClient() {
return AwsToolkitCore.getClientFactory(getAccountId())
.getLambdaClientByRegion(getRegionId());
}
}
| 7,852 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionLogsTable.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.explorer.lambda;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreePathContentProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
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.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.ide.IDE;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.invoke.logs.CloudWatchLogsUtils;
import com.amazonaws.services.logs.AWSLogs;
import com.amazonaws.services.logs.model.LogStream;
import com.amazonaws.services.logs.model.OutputLogEvent;
import com.amazonaws.util.IOUtils;
import com.amazonaws.util.StringInputStream;
public class FunctionLogsTable extends Composite {
private TreeViewer viewer;
private final FunctionEditorInput functionEditorInput;
private final class FunctionLogsContentProvider implements ITreePathContentProvider {
private LogStream[] logStreams;
@Override
public void dispose() {}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof LogStream[]) {
logStreams = (LogStream[])newInput;
} else {
logStreams = new LogStream[0];
}
}
@Override
public Object[] getElements(Object inputElement) {
return logStreams;
}
@Override
public Object[] getChildren(TreePath parentPath) {
return null;
}
@Override
public boolean hasChildren(TreePath path) {
return false;
}
@Override
public TreePath[] getParents(Object element) {
return new TreePath[0];
}
}
private final class FunctionLogsLabelProvider 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 LogStream == false) return "";
LogStream logStream = (LogStream)element;
switch (columnIndex) {
case 0: return logStream.getLogStreamName();
case 1: return CloudWatchLogsUtils.longTimeToHumanReadible(logStream.getCreationTime());
case 2: return CloudWatchLogsUtils.longTimeToHumanReadible(logStream.getLastEventTimestamp());
case 3: return logStream.getStoredBytes().toString();
}
return element.toString();
}
}
public FunctionLogsTable(Composite parent, FormToolkit toolkit, FunctionEditorInput functionEditorInput) {
super(parent, SWT.NONE);
this.functionEditorInput = functionEditorInput;
this.setLayout(new GridLayout());
Composite composite = toolkit.createComposite(this);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TreeColumnLayout tableColumnLayout = new TreeColumnLayout();
composite.setLayout(tableColumnLayout);
FunctionLogsContentProvider contentProvider = new FunctionLogsContentProvider();
FunctionLogsLabelProvider labelProvider = new FunctionLogsLabelProvider();
viewer = new TreeViewer(composite, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.getTree().setLinesVisible(true);
viewer.getTree().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTree());
refresh();
hookContextMenu();
}
public void refresh() {
new LoadFunctionLogsThread().start();
}
private List<LogStream> getSelectedObjects() {
IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
List<LogStream> streams = new LinkedList<>();
Iterator<?> iterator = selection.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
if (next instanceof LogStream) {
streams.add((LogStream) next);
}
}
return streams;
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
manager.add(new ShowLogEventsAction());
}
});
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
menuMgr.createContextMenu(this);
viewer.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent e) {
new ShowLogEventsAction().run();
}
});
}
private void createColumns(TreeColumnLayout columnLayout, Tree tree) {
createColumn(tree, columnLayout, "Log Streams");
createColumn(tree, columnLayout, "Creation Time");
createColumn(tree, columnLayout, "Last Event Time");
createColumn(tree, columnLayout, "Stored Bytes");
}
private TreeColumn createColumn(Tree tree, TreeColumnLayout columnLayout, String text) {
TreeColumn column = new TreeColumn(tree, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
private AWSLogs getLogsClient() {
return AwsToolkitCore.getClientFactory(functionEditorInput.getAccountId())
.getLogsClientByRegion(functionEditorInput.getRegionId());
}
private String getLogGroupName() {
return "/aws/lambda/" + functionEditorInput.getFunctionName();
}
private class LoadFunctionLogsThread extends Thread {
@Override
public void run() {
try {
AWSLogs logsClient = getLogsClient();
String logGroupName = getLogGroupName();
final List<LogStream> logStreams = CloudWatchLogsUtils.listLogStreams(logsClient, logGroupName);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(logStreams.toArray(new LogStream[logStreams.size()]));
}
});
} catch (Exception e) {
LambdaPlugin.getDefault().reportException("Unable to describe log streams for function " + functionEditorInput.getFunctionName(), e);
}
}
}
private class ShowLogEventsAction extends Action {
public ShowLogEventsAction() {
this.setText("Show Log Events");
}
@Override
public void run() {
AWSLogs logClient = getLogsClient();
String logGroupName = getLogGroupName();
List<LogStream> selectedStreams = getSelectedObjects();
try {
List<OutputLogEvent> events = CloudWatchLogsUtils.listLogEvents(logClient, logGroupName, selectedStreams);
String text = CloudWatchLogsUtils.convertLogEventsToString(events);
File file = File.createTempFile(logGroupName, ".txt");
IOUtils.copy(new StringInputStream(text), new FileOutputStream(file));
IFileStore fileStore = EFS.getLocalFileSystem().getStore(file.toURI());
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IDE.openEditorOnFileStore( page, fileStore );
} catch (Exception e) {
MessageDialog.openError(getShell(), "Failed to open function Log Events", e.getMessage());
}
}
}
}
| 7,853 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/LambdaTagNameValidator.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.explorer.lambda;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
public class LambdaTagNameValidator implements IValidator {
/* (non-Javadoc)
* @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
*/
@Override
public IStatus validate(Object value) {
String name = (String) value;
if (name.startsWith("aws:")) {
return ValidationStatus.error("Keys cannot begin with \"aws:\" because it is reserved for AWS use");
}
return ValidationStatus.ok();
}
}
| 7,854 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionTagsTable.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.explorer.lambda;
import static com.amazonaws.eclipse.lambda.LambdaConstants.MAX_LAMBDA_TAGS;
import static com.amazonaws.eclipse.lambda.LambdaConstants.MAX_LAMBDA_TAG_KEY_LENGTH;
import static com.amazonaws.eclipse.lambda.LambdaConstants.MAX_LAMBDA_TAG_VALUE_LENGTH;
import java.util.ArrayList;
import java.util.HashMap;
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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.model.KeyValueSetDataModel;
import com.amazonaws.eclipse.core.model.KeyValueSetDataModel.Pair;
import com.amazonaws.eclipse.core.ui.KeyValueSetEditingComposite;
import com.amazonaws.eclipse.core.ui.KeyValueSetEditingComposite.KeyValueSetEditingCompositeBuilder;
import com.amazonaws.eclipse.core.validator.StringLengthValidator;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.model.AWSLambdaException;
import com.amazonaws.services.lambda.model.ListTagsRequest;
import com.amazonaws.services.lambda.model.TagResourceRequest;
import com.amazonaws.services.lambda.model.UntagResourceRequest;
public class FunctionTagsTable extends Composite {
private final FunctionEditorInput functionEditorInput;
private final KeyValueSetEditingComposite tagsEditingComposite;
private final KeyValueSetDataModel tagsDataModel;
public FunctionTagsTable(Composite parent, FormToolkit toolkit, FunctionEditorInput functionEditorInput) {
super(parent, SWT.NONE);
this.functionEditorInput = functionEditorInput;
this.setLayout(new GridLayout());
this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
tagsDataModel = new KeyValueSetDataModel(MAX_LAMBDA_TAGS, new ArrayList<Pair>());
tagsEditingComposite = new KeyValueSetEditingCompositeBuilder()
.addKeyValidator(new StringLengthValidator(1, MAX_LAMBDA_TAG_KEY_LENGTH,
String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_KEY_LENGTH)))
.addValueValidator(new StringLengthValidator(0, MAX_LAMBDA_TAG_VALUE_LENGTH,
String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_VALUE_LENGTH)))
.addKeyValidator(new LambdaTagNameValidator())
.saveListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onSaveTags();
}
})
.build(this, tagsDataModel);
Composite buttonComposite = new Composite(this, SWT.NONE);
buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
buttonComposite.setLayout(new GridLayout(1, false));
refresh();
}
public void refresh() {
Map<String, String> tagMap = functionEditorInput.getLambdaClient()
.listTags(new ListTagsRequest()
.withResource(functionEditorInput.getFunctionArn()))
.getTags();
tagsDataModel.getPairSet().clear();
for (Entry<String, String> entry : tagMap.entrySet()) {
tagsDataModel.getPairSet().add(new Pair(entry.getKey(), entry.getValue()));
}
tagsEditingComposite.refresh();
}
private void onSaveTags() {
try {
AWSLambda lambda = functionEditorInput.getLambdaClient();
Map<String, String> oldTagMap = lambda
.listTags(new ListTagsRequest()
.withResource(functionEditorInput.getFunctionArn()))
.getTags();
List<String> tagKeysToBeRemoved = new ArrayList<>();
for (String key : oldTagMap.keySet()) {
if (!tagsDataModel.getPairSet().contains(key)) {
tagKeysToBeRemoved.add(key);
}
}
Map<String, String> tagMap = new HashMap<>();
for (Pair pair : tagsDataModel.getPairSet()) {
tagMap.put(pair.getKey(), pair.getValue());
}
if (!tagKeysToBeRemoved.isEmpty()) {
lambda.untagResource(new UntagResourceRequest()
.withResource(functionEditorInput.getFunctionArn())
.withTagKeys(tagKeysToBeRemoved));
}
lambda.tagResource(new TagResourceRequest()
.withResource(functionEditorInput.getFunctionArn())
.withTags(tagMap));
} catch (AWSLambdaException e) {
LambdaPlugin.getDefault().reportException(e.getMessage(), e);
}
}
}
| 7,855 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/LambdaContentProvider.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.explorer.lambda;
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;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.LambdaUtils;
import com.amazonaws.eclipse.lambda.LambdaUtils.FunctionConfigurationConverter;
import com.amazonaws.services.lambda.model.FunctionConfiguration;
public class LambdaContentProvider extends AbstractContentProvider {
public static final class LambdaRootElement {
public static final LambdaRootElement ROOT_ELEMENT = new LambdaRootElement();
}
public static class FunctionNode extends ExplorerNode {
private final FunctionConfiguration function;
public FunctionNode(FunctionConfiguration function) {
super(function.getFunctionName(), 0,
loadImage(LambdaPlugin.getDefault(), LambdaPlugin.IMAGE_FUNCTION),
new OpenFunctionEditorAction(function.getFunctionArn(), function.getFunctionName()));
this.function = function;
}
}
@Override
public boolean hasChildren(Object element) {
return (element instanceof AWSResourcesRootElement ||
element instanceof LambdaRootElement);
}
@Override
public Object[] loadChildren(Object parentElement) {
if (parentElement instanceof AWSResourcesRootElement) {
return new Object[] {LambdaRootElement.ROOT_ELEMENT};
}
if (parentElement instanceof LambdaRootElement) {
new DataLoaderThread(parentElement) {
@Override
public Object[] loadData() {
return LambdaUtils.listFunctions(new FunctionConfigurationConverter<FunctionNode>() {
@Override
public FunctionNode convert(FunctionConfiguration function) {
return new FunctionNode(function);
}
}).toArray();
}
}.start();
}
return Loading.LOADING;
}
@Override
public String getServiceAbbreviation() {
return ServiceAbbreviations.LAMBDA;
}
}
| 7,856 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/OpenFunctionEditorAction.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.explorer.lambda;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
public class OpenFunctionEditorAction extends Action {
private final String functionArn;
private final String functionName;
public OpenFunctionEditorAction(String functionArn, String functionName) {
this.setText("Open in Function Editor");
this.functionArn = functionArn;
this.functionName = functionName;
}
@Override
public void run() {
String regionId = RegionUtils.getCurrentRegion().getId();
String accountId = AwsToolkitCore.getDefault().getCurrentAccountId();
final IEditorInput input = new FunctionEditorInput(accountId, regionId, functionArn, functionName);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
activeWindow.getActivePage().openEditor(input, "com.amazonaws.eclipse.explorer.lambda.FunctionEditor");
} catch (PartInitException e) {
LambdaPlugin.getDefault().reportException("Unable to open the AWS Lambda function editor.", e);
}
}
});
}
}
| 7,857 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionEditor.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.explorer.lambda;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.services.lambda.model.FunctionConfiguration;
import com.amazonaws.services.lambda.model.GetFunctionRequest;
import com.amazonaws.services.lambda.model.GetFunctionResult;
public class FunctionEditor extends EditorPart {
private FunctionEditorInput functionEditorInput;
private Text functionNameLabel;
private Text arnLabel;
private Text runtimeLabel;
private Text handlerLabel;
private Text roleLabel;
private Text lastUpdatedLabel;
private Text memorySizeLabel;
private Text timeoutLabel;
private Text codeSizeLabel;
private Text descriptionLabel;
private FunctionLogsTable functionLogsTable;
private FunctionTagsTable functionTagsTable;
private FunctionEnvVarsTable functionEnvVarsTable;
private RefreshAction refreshAction;
@Override
public void doSave(IProgressMonitor monitor) {}
@Override
public void doSaveAs() {}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
setPartName(input.getName());
this.functionEditorInput = (FunctionEditorInput) input;
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void createPartControl(Composite parent) {
FormToolkit toolkit = new FormToolkit(Display.getDefault());
ScrolledForm form = new ScrolledForm(parent, SWT.V_SCROLL | SWT.H_SCROLL);
form.setExpandHorizontal(true);
form.setExpandVertical(true);
form.setBackground(toolkit.getColors().getBackground());
form.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
form.setFont(JFaceResources.getHeaderFont());
form.setText(getFormTitle());
toolkit.decorateFormHeading(form.getForm());
form.setImage(getDefaultImage());
form.getBody().setLayout(new GridLayout());
createSummarySection(form.getBody(), toolkit);
createTabsSection(form.getBody(), toolkit);
refreshAction = new RefreshAction();
form.getToolBarManager().add(refreshAction);
form.getToolBarManager().update(true);
new LoadFunctionConfigurationThread().start();
}
private void createSummarySection(Composite parent, FormToolkit toolkit) {
GridDataFactory gridDataFactory = GridDataFactory.swtDefaults()
.align(SWT.FILL, SWT.TOP).grab(true, false).minSize(200, SWT.DEFAULT).hint(200, SWT.DEFAULT);
Composite composite = toolkit.createComposite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
composite.setLayout(new GridLayout(4, false));
toolkit.createLabel(composite, "Function Name:");
functionNameLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(functionNameLabel);
toolkit.createLabel(composite, "ARN:");
arnLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(arnLabel);
toolkit.createLabel(composite, "Runtime:");
runtimeLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(runtimeLabel);
toolkit.createLabel(composite, "Role:");
roleLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(roleLabel);
toolkit.createLabel(composite, "Handler:");
handlerLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(handlerLabel);
toolkit.createLabel(composite, "Last Updated:");
lastUpdatedLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(lastUpdatedLabel);
toolkit.createLabel(composite, "Memory Size (MB):");
memorySizeLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(memorySizeLabel);
toolkit.createLabel(composite, "Timeout (sec):");
timeoutLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(timeoutLabel);
toolkit.createLabel(composite, "Code Size:");
codeSizeLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
toolkit.createLabel(composite, "");
toolkit.createLabel(composite, "");
Label l = toolkit.createLabel(composite, "Description:");
gridDataFactory.copy().hint(100, SWT.DEFAULT).minSize(1, SWT.DEFAULT).align(SWT.LEFT, SWT.TOP).grab(false, false).applyTo(l);
descriptionLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE | SWT.MULTI | SWT.WRAP);
gridDataFactory.copy().span(3, 1).applyTo(descriptionLabel);
}
private void createTabsSection(Composite parent, FormToolkit toolkit) {
Composite tabsSection = toolkit.createComposite(parent, SWT.NONE);
tabsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
tabsSection.setLayout(new FillLayout());
TabFolder tabFolder = new TabFolder (tabsSection, SWT.BORDER);
Rectangle clientArea = parent.getClientArea();
tabFolder.setLocation(clientArea.x, clientArea.y);
TabItem eventsTab = new TabItem(tabFolder, SWT.NONE);
eventsTab.setText("Logs");
functionLogsTable = new FunctionLogsTable(tabFolder, toolkit, functionEditorInput);
eventsTab.setControl(functionLogsTable);
TabItem tagsTab = new TabItem(tabFolder, SWT.NONE);
tagsTab.setText("Tags");
functionTagsTable = new FunctionTagsTable(tabFolder, toolkit, functionEditorInput);
tagsTab.setControl(functionTagsTable);
TabItem envVarsTab = new TabItem(tabFolder, SWT.NONE);
envVarsTab.setText("Environment Variables");
functionEnvVarsTable = new FunctionEnvVarsTable(tabFolder, toolkit, functionEditorInput);
envVarsTab.setControl(functionEnvVarsTable);
tabFolder.pack();
}
@Override
public void setFocus() {}
private String getFormTitle() {
return functionEditorInput.getName() + "-" + RegionUtils.getRegion(functionEditorInput.getRegionId()).getName();
}
private class RefreshAction extends Action {
public RefreshAction() {
this.setText("Refresh");
this.setToolTipText("Refresh function information");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH));
}
@Override
public void run() {
new LoadFunctionConfigurationThread().start();
functionLogsTable.refresh();
functionTagsTable.refresh();
functionEnvVarsTable.refresh();
}
}
private class LoadFunctionConfigurationThread extends Thread {
private GetFunctionResult getFunction(String functionName) {
return functionEditorInput.getLambdaClient().getFunction(new GetFunctionRequest()
.withFunctionName(functionName));
}
@Override
public void run() {
try {
final GetFunctionResult getFunctionResult = getFunction(functionEditorInput.getFunctionName());
final FunctionConfiguration configuration = getFunctionResult.getConfiguration();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
functionNameLabel.setText(configuration.getFunctionName());
arnLabel.setText(configuration.getFunctionArn());
runtimeLabel.setText(configuration.getRuntime());
handlerLabel.setText(valueOrDefault(configuration.getHandler(), "N/A"));
roleLabel.setText(valueOrDefault(configuration.getRole(), "N/A"));
lastUpdatedLabel.setText(valueOrDefault(configuration.getLastModified(), "N/A"));
memorySizeLabel.setText(valueOrDefault(configuration.getMemorySize().toString(), "N/A"));
timeoutLabel.setText(valueOrDefault(configuration.getTimeout().toString(), "N/A"));
codeSizeLabel.setText(valueOrDefault(configuration.getCodeSize().toString(), "N/A"));
descriptionLabel.setText(valueOrDefault(configuration.getDescription(), ""));
functionNameLabel.getParent().layout();
functionNameLabel.getParent().getParent().layout(true);
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, LambdaPlugin.PLUGIN_ID, "Unable to describe function " + functionEditorInput.getName(), e);
StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW);
}
}
private String valueOrDefault(String value, String defaultValue) {
if (value != null) return value;
else return defaultValue;
}
}
}
| 7,858 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/LambdaUtils.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.lambda;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.model.AliasConfiguration;
import com.amazonaws.services.lambda.model.FunctionConfiguration;
import com.amazonaws.services.lambda.model.ListAliasesRequest;
import com.amazonaws.services.lambda.model.ListAliasesResult;
import com.amazonaws.services.lambda.model.ListFunctionsRequest;
import com.amazonaws.services.lambda.model.ListFunctionsResult;
public class LambdaUtils {
/**
* Retrieve all the Lambda functions with the default setting and convert them to the specified type.
*/
public static <T> List<T> listFunctions(FunctionConfigurationConverter<T> converter) {
AWSLambda lambda = AwsToolkitCore.getClientFactory().getLambdaClient();
List<T> newItems = new ArrayList<>();
ListFunctionsRequest request = new ListFunctionsRequest();
ListFunctionsResult result = null;
do {
result = lambda.listFunctions(request);
for (FunctionConfiguration function : result.getFunctions()) {
newItems.add(converter.convert(function));
}
request.setMarker(result.getNextMarker());
} while (result.getNextMarker() != null);
return newItems;
}
public static List<AliasConfiguration> listFunctionAlias(String accountId, String regionId, String functionName) {
if (functionName == null) {
return Collections.emptyList();
}
AWSLambda lambdaClient = AwsToolkitCore.getClientFactory(accountId).getLambdaClientByRegion(regionId);
List<AliasConfiguration> aliasList = new ArrayList<>();
ListAliasesRequest request = new ListAliasesRequest().withFunctionName(functionName);
ListAliasesResult result = null;
do {
result = lambdaClient.listAliases(request);
aliasList.addAll(result.getAliases());
request.setMarker(result.getNextMarker());
} while (result.getNextMarker() != null);
return aliasList;
}
public interface FunctionConfigurationConverter<T> {
T convert(FunctionConfiguration function);
}
}
| 7,859 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/ServiceApiUtils.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.lambda;
import java.net.URLDecoder;
import java.util.LinkedList;
import java.util.List;
import com.amazonaws.auth.policy.Action;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.auth.policy.Principal;
import com.amazonaws.auth.policy.Statement;
import com.amazonaws.auth.policy.Statement.Effect;
import com.amazonaws.auth.policy.actions.SecurityTokenServiceActions;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.ListRolesRequest;
import com.amazonaws.services.identitymanagement.model.ListRolesResult;
import com.amazonaws.services.identitymanagement.model.Role;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.model.FunctionConfiguration;
import com.amazonaws.services.lambda.model.ListFunctionsRequest;
import com.amazonaws.services.lambda.model.ListFunctionsResult;
public class ServiceApiUtils {
public static final String JAVA_8 = "java8";
private static final String LAMBDA_DOT_AMAZONAWS_DOT_COM = "lambda.amazonaws.com";
public static List<FunctionConfiguration> getAllJavaFunctions(AWSLambda lambda) {
List<FunctionConfiguration> allJavaFunctions = new LinkedList<>();
String nextMarker = null;
do {
ListFunctionsResult result = lambda.listFunctions
(new ListFunctionsRequest()
.withMarker(nextMarker));
List<FunctionConfiguration> functions = result.getFunctions();
if (functions != null) {
for (FunctionConfiguration function : functions) {
if (isJavaFunction(function)) {
allJavaFunctions.add(function);
}
}
}
nextMarker = result.getNextMarker();
} while (nextMarker != null);
return allJavaFunctions;
}
/**
* @return all the roles that are allowed to be assumed by AWS Lambda service
*/
public static List<Role> getAllLambdaRoles(AmazonIdentityManagement iam) {
List<Role> allRoles = new LinkedList<>();
String nextMarker = null;
do {
ListRolesResult result = iam.listRoles(
new ListRolesRequest()
.withMarker(nextMarker));
List<Role> roles = result.getRoles();
if (roles != null) {
for (Role role : roles) {
if (canBeAssumedByLambda(role)) {
allRoles.add(role);
}
}
}
nextMarker = result.getMarker();
} while (nextMarker != null);
return allRoles;
}
private static boolean isJavaFunction(FunctionConfiguration function) {
return JAVA_8.equals(function.getRuntime());
}
private static boolean canBeAssumedByLambda(Role role) {
if (role.getAssumeRolePolicyDocument() == null) {
return false;
}
Policy assumeRolePolicy;
try {
String policyJson = URLDecoder.decode(role.getAssumeRolePolicyDocument(), "UTF-8");
assumeRolePolicy = Policy.fromJson(policyJson);
} catch (Exception e) {
LambdaPlugin.getDefault().logWarning(
"Failed to parse assume role policy for ["
+ role.getRoleName() + "]. "
+ role.getAssumeRolePolicyDocument(), e);
return false;
}
for (Statement statement : assumeRolePolicy.getStatements()) {
if (statement.getEffect() == Effect.Allow
&& hasStsAssumeRoleAction(statement.getActions())
&& hasLambdaServicePrincipal(statement.getPrincipals())) {
return true;
}
}
return false;
}
private static boolean hasStsAssumeRoleAction(List<Action> actions) {
if (actions == null) {
return false;
}
for (Action action : actions) {
if (action.getActionName().equalsIgnoreCase(
SecurityTokenServiceActions.AllSecurityTokenServiceActions
.getActionName())) {
return true;
}
if (action.getActionName().equalsIgnoreCase(
SecurityTokenServiceActions.AssumeRole.getActionName())) {
return true;
}
}
return false;
}
private static boolean hasLambdaServicePrincipal(List<Principal> principals) {
if (principals == null) {
return false;
}
for (Principal principal : principals) {
if (principal.equals(Principal.All)) {
return true;
}
if (principal.equals(Principal.AllServices)) {
return true;
}
if (principal.getProvider().equalsIgnoreCase("Service")
&& principal.getId().equalsIgnoreCase(LAMBDA_DOT_AMAZONAWS_DOT_COM)) {
return true;
}
}
return false;
}
}
| 7,860 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/LambdaPlugin.java | /*
* Copyright 2015 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.lambda;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.BundleContext;
import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin;
import com.amazonaws.eclipse.lambda.project.listener.LambdaProjectChangeTracker;
/**
* The activator class controls the plug-in life cycle
*/
public class LambdaPlugin extends AbstractAwsPlugin {
public static final String PLUGIN_ID = "com.amazonaws.eclipse.lambda";
public static final String DEFAULT_REGION = "us-east-1";
public static final String IMAGE_LAMBDA = "lambda-service";
public static final String IMAGE_FUNCTION = "function";
public static final String IMAGE_SAM_LOCAL = "sam-local";
private static final Map<String, String> IMAGE_REGISTRY_MAP = new HashMap<>();
static {
IMAGE_REGISTRY_MAP.put(IMAGE_LAMBDA, "/icons/lambda-service.png");
IMAGE_REGISTRY_MAP.put(IMAGE_FUNCTION, "/icons/function.png");
IMAGE_REGISTRY_MAP.put(IMAGE_SAM_LOCAL, "/icons/sam-local.png");
}
/*
* Preference store keys
*/
public static final String PREF_K_SHOW_README_AFTER_CREATE_NEW_PROJECT = "showReadmeAfterCreateNewProject";
/** The shared instance */
private static LambdaPlugin plugin;
private final LambdaProjectChangeTracker projectChangeTracker = new LambdaProjectChangeTracker();
/**
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
initializePreferenceStoreDefaults();
projectChangeTracker.clearDirtyFlags();
projectChangeTracker.start();
}
/**
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
projectChangeTracker.clearDirtyFlags();
projectChangeTracker.stop();
super.stop(context);
}
private void initializePreferenceStoreDefaults() {
getPreferenceStore().setDefault(PREF_K_SHOW_README_AFTER_CREATE_NEW_PROJECT, true);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static LambdaPlugin getDefault() {
return plugin;
}
public LambdaProjectChangeTracker getProjectChangeTracker() {
return projectChangeTracker;
}
/**
* Print the message in system.out if Eclipse is running in debugging mode.
*/
public void trace(String message) {
if (Platform.inDebugMode()) {
System.out.println(message);
}
}
@Override
protected Map<String, String> getImageRegistryMap() {
return IMAGE_REGISTRY_MAP;
}
}
| 7,861 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/LambdaAnalytics.java | /*
* Copyright 2015-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.lambda;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.ToolkitAnalyticsManager;
import com.amazonaws.eclipse.core.telemetry.ToolkitEvent.ToolkitEventBuilder;
import com.amazonaws.eclipse.lambda.project.wizard.model.LambdaFunctionWizardDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.model.NewServerlessProjectDataModel;
public final class LambdaAnalytics {
/*
* Upload function wizard
*/
private static final String EVENT_TYPE_UPLOAD_FUNCTION_WIZARD = "lambda_deploy";
// OpenedFrom -> ProjectContextMenu/FileEditorContextMenu
private static final String ATTR_NAME_OPENED_FROM = "OpenedFrom";
private static final String ATTR_VALUE_PROJECT_CONTEXT_MENU = "ProjectContextMenu";
private static final String ATTR_VALUE_FILE_EDITOR_CONTEXT_MENU = "FileEditorContextMenu";
private static final String ATTR_VALUE_UPLOAD_BEFORE_INVOKE = "UploadBeforeInvoke";
private static final String ATTR_NAME_CHANGE_SELECTION = "ChangeSelection";
private static final String ATTR_VALUE_REGION_SELECTION_COMBO = "RegionSelectionCombo";
private static final String ATTR_VALUE_FUNCTION_HANDLER_SELECTION_COMBO = "FunctionHandlerSelectionCombo";
private static final String ATTR_VALUE_IAM_ROLE_SELECTION_COMBO = "IamRoleSelectionCombo";
private static final String ATTR_VALUE_S3_BUCKET_SELECTION_COMBO = "S3BucketSelectionCombo";
private static final String ATTR_NAME_CLICK = "Click";
private static final String ATTR_VALUE_CREATE_IAM_ROLE_BUTTON = "CreateIamRoleButton";
private static final String ATTR_VALUE_CREATE_S3_BUCKET_BUTTON = "CreateS3BucketButton";
private static final String METRIC_NAME_UPLOAD_TOTAL_TIME_DURATION_MS = "UploadTotalTimeDurationMs";
private static final String METRIC_NAME_UPLOAD_S3_BUCKET_TIME_DURATION_MS = "UploadS3BucketTimeDurationMs";
private static final String METRIC_NAME_EXPORTED_JAR_SIZE = "ExportedJarSize";
private static final String METRIC_NAME_UPLOAD_S3_BUCKET_SPEED = "UploadSpeed";
private static final String METRIC_NAME_IS_CREATING_NEW_FUNCTION = "IsCreatingNewFunction";
private static final String METRIC_NAME_VALID_FUNCTION_HANDLER_CLASS_COUNT = "ValidFunctionHandlerClassCount";
private static final String METRIC_NAME_LOAD_IAM_ROLE_TIME_DURATION_MS = "LoadIamRoleTimeDurationMs";
private static final String METRIC_NAME_LOAD_S3_BUCKET_TIME_DURATION_MS = "LoadS3BucketTimeDurationMs";
/*
* Invoke function dialog
*/
private static final String EVENT_TYPE_INVOKE_FUNCTION = "lambda_invokeRemote";
// Change selection
private static final String ATTR_VALUE_INVOKE_INPUT_FILE_SELECTION_COMBO = "InvokeInputFileSelectionCombo";
private static final String METRIC_NAME_FUNCTION_LOG_LENGTH = "FunctionLogLength";
private static final String METRIC_NAME_SHOW_LIVE_LOG = "ShowLiveLog";
/*
* New wizard
*/
private static final String EVENT_TYPE_NEW_LAMBDA_PROJECT_WIZARD = "project_new";
private static final String EVENT_TYPE_NEW_LAMBDA_FUNCTION_WIZARD = "project_new";
private static final String EVENT_TYPE_NEW_SERVERLESS_PROJECT_WIZARD = "sam_init";
private static final String EVENT_TYPE_DEPLOY_SERVERLESS_PROJECT_WIZARD = "sam_deploy";
private static final String ATTR_NAME_FUNCTION_INPUT_TYPE = "FunctionInputType";
private static final String ATTR_NAME_BLUEPRINT_NAME = "BlueprintName";
private static final String ATTR_NAME_IS_IMPORT_TEMPLATE = "IsImportTemplate";
// End result -> Succeeded/Failed/Canceled
private static final String ATTR_NAME_END_RESULT = "result";
private static final String ATTR_VALUE_SUCCEEDED = "Succeeded";
private static final String ATTR_VALUE_FAILED = "Failed";
private static final String ATTR_VALUE_CANCELED = "Canceled";
private static final ToolkitAnalyticsManager ANALYTICS = AwsToolkitCore.getDefault().getAnalyticsManager();
/*
* Analytics for Lambda-NewLambdaProjectWizard
*/
public static void trackProjectCreationSucceeded() {
publishEventWithAttributes(EVENT_TYPE_NEW_LAMBDA_PROJECT_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_SUCCEEDED);
}
public static void trackProjectCreationFailed() {
publishEventWithAttributes(EVENT_TYPE_NEW_LAMBDA_PROJECT_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_FAILED);
}
public static void trackProjectCreationCanceled() {
publishEventWithAttributes(EVENT_TYPE_NEW_LAMBDA_PROJECT_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_CANCELED);
}
public static void trackNewProjectAttributes(LambdaFunctionWizardDataModel dataModel) {
publishEventWithAttributes(EVENT_TYPE_NEW_LAMBDA_PROJECT_WIZARD, ATTR_NAME_FUNCTION_INPUT_TYPE,
dataModel.getLambdaFunctionDataModel().getInputType());
}
/*
* Analytics for Lambda-NewLambdaFunctionWizard
*/
public static void trackLambdaFunctionCreationFailed() {
publishEventWithAttributes(EVENT_TYPE_NEW_LAMBDA_FUNCTION_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_FAILED);
}
public static void trackLambdaFunctionCreationSucceeded() {
publishEventWithAttributes(EVENT_TYPE_NEW_LAMBDA_FUNCTION_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_SUCCEEDED);
}
public static void trackLambdaFunctionCreationCanceled() {
publishEventWithAttributes(EVENT_TYPE_NEW_LAMBDA_FUNCTION_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_CANCELED);
}
/*
* Analytics for Lambda-NewServerlessProjectWizard
*/
public static void trackServerlessProjectCreationSucceeded() {
publishEventWithAttributes(EVENT_TYPE_NEW_SERVERLESS_PROJECT_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_SUCCEEDED);
}
public static void trackServerlessProjectCreationFailed() {
publishEventWithAttributes(EVENT_TYPE_NEW_SERVERLESS_PROJECT_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_FAILED);
}
public static void trackServerlessProjectCreationCanceled() {
publishEventWithAttributes(EVENT_TYPE_NEW_SERVERLESS_PROJECT_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_CANCELED);
}
public static void trackServerlessProjectSelection(NewServerlessProjectDataModel dataModel) {
if (dataModel.isUseBlueprint()) {
publishEventWithAttributes(EVENT_TYPE_NEW_SERVERLESS_PROJECT_WIZARD, ATTR_NAME_BLUEPRINT_NAME, dataModel.getBlueprintName());
}
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_NEW_SERVERLESS_PROJECT_WIZARD)
.addBooleanMetric(ATTR_NAME_IS_IMPORT_TEMPLATE, !dataModel.isUseBlueprint())
.build());
}
/*
* Analytics for Lambda-DeployServerlessProjectWizard
*/
public static void trackDeployServerlessProjectSucceeded() {
publishEventWithAttributes(EVENT_TYPE_DEPLOY_SERVERLESS_PROJECT_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_SUCCEEDED);
}
public static void trackDeployServerlessProjectFailed() {
publishEventWithAttributes(EVENT_TYPE_DEPLOY_SERVERLESS_PROJECT_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_FAILED);
}
public static void trackDeployServerlessProjectCanceled() {
publishEventWithAttributes(EVENT_TYPE_DEPLOY_SERVERLESS_PROJECT_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_CANCELED);
}
public static void trackInvokeSucceeded() {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_INVOKE_FUNCTION)
.addAttribute(ATTR_NAME_END_RESULT, ATTR_VALUE_SUCCEEDED)
.build());
}
public static void trackInvokeFailed() {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_INVOKE_FUNCTION)
.addAttribute(ATTR_NAME_END_RESULT, ATTR_VALUE_FAILED)
.build());
}
public static void trackInvokeCanceled() {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_INVOKE_FUNCTION)
.addAttribute(ATTR_NAME_END_RESULT, ATTR_VALUE_CANCELED)
.build());
}
/*
* Analytics for Lambda-UploadFunctionWizard
*/
public static void trackUploadWizardOpenedFromEditorContextMenu() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_OPENED_FROM, ATTR_VALUE_FILE_EDITOR_CONTEXT_MENU);
}
public static void trackUploadWizardOpenedBeforeFunctionInvoke() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_OPENED_FROM, ATTR_VALUE_UPLOAD_BEFORE_INVOKE);
}
public static void trackUploadWizardOpenedFromProjectContextMenu() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_OPENED_FROM, ATTR_VALUE_PROJECT_CONTEXT_MENU);
}
public static void trackFunctionHandlerComboSelectionChange() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_CHANGE_SELECTION, ATTR_VALUE_FUNCTION_HANDLER_SELECTION_COMBO);
}
public static void trackRoleComboSelectionChange() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_CHANGE_SELECTION, ATTR_VALUE_IAM_ROLE_SELECTION_COMBO);
}
public static void trackS3BucketComboSelectionChange() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_CHANGE_SELECTION, ATTR_VALUE_S3_BUCKET_SELECTION_COMBO);
}
public static void trackRegionComboChangeSelection() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_CHANGE_SELECTION, ATTR_VALUE_REGION_SELECTION_COMBO);
}
public static void trackClickCreateNewRoleButton() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_CLICK, ATTR_VALUE_CREATE_IAM_ROLE_BUTTON);
}
public static void trackClickCreateNewBucketButton() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_CLICK, ATTR_VALUE_CREATE_S3_BUCKET_BUTTON);
}
public static void trackLoadRoleTimeDuration(long duration) {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD)
.addMetric(METRIC_NAME_LOAD_IAM_ROLE_TIME_DURATION_MS, duration)
.build());
}
public static void trackLoadBucketTimeDuration(long duration) {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD)
.addMetric(METRIC_NAME_LOAD_S3_BUCKET_TIME_DURATION_MS, duration)
.build());
}
public static void trackMetrics(boolean isCreatingNewFunction, int validFunctionHandlerClassCount) {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD)
.addBooleanMetric(METRIC_NAME_IS_CREATING_NEW_FUNCTION, isCreatingNewFunction)
.addMetric(METRIC_NAME_VALID_FUNCTION_HANDLER_CLASS_COUNT, validFunctionHandlerClassCount)
.build());
}
public static void trackUploadSucceeded() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_SUCCEEDED);
}
public static void trackUploadFailed() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_FAILED);
}
public static void trackUploadCanceled() {
publishEventWithAttributes(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD, ATTR_NAME_END_RESULT, ATTR_VALUE_CANCELED);
}
public static void trackUploadTotalTime(long uploadTotalTime) {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD)
.addMetric(METRIC_NAME_UPLOAD_TOTAL_TIME_DURATION_MS, uploadTotalTime)
.build());
}
public static void trackUploadS3BucketTime(long uploadS3BucketTime) {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD)
.addMetric(METRIC_NAME_UPLOAD_S3_BUCKET_TIME_DURATION_MS, uploadS3BucketTime)
.build());
}
public static void trackExportedJarSize(long exportedJarSize) {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD)
.addMetric(METRIC_NAME_EXPORTED_JAR_SIZE, exportedJarSize)
.build());
}
public static void trackUploadS3BucketSpeed(double uploadS3BucketSpeed) {
ANALYTICS.publishEvent(ANALYTICS.eventBuilder()
.setEventType(EVENT_TYPE_UPLOAD_FUNCTION_WIZARD)
.addMetric(METRIC_NAME_UPLOAD_S3_BUCKET_SPEED, uploadS3BucketSpeed)
.build());
}
private static void publishEventWithAttributes(String eventType, String... attributes) {
ToolkitEventBuilder builder = ANALYTICS.eventBuilder().setEventType(eventType);
for (int i = 0; i < attributes.length; i += 2) {
builder.addAttribute(attributes[i], attributes[i + 1]);
}
ANALYTICS.publishEvent(builder.build());
}
}
| 7,862 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/LambdaConstants.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.lambda;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
public class LambdaConstants {
public static final String LAMBDA_JAVA_HANDLER_DOC_URL = "https://docs.aws.amazon.com/lambda/latest/dg/programming-model.html";
public static final String LAMBDA_EXECUTION_ROLE_DOC_URL = "https://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role";
public static final String CLOUDFORMATION_CAPABILITIES = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities";
public static final String LAMBDA_REQUEST_HANDLER_DOC_URL = "https://docs.aws.amazon.com/lambda/latest/dg/java-programming-model-req-resp.html";
public static final String LAMBDA_STREAM_REQUEST_HANDLER_DOC_URL = "https://docs.aws.amazon.com/lambda/latest/dg/java-handler-io-type-stream.html";
public static final String LAMBDA_FUNCTION_VERSIONING_AND_ALIASES_URL = "http://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html";
public static final String LAMBDA_FUNCTION_ENCRYPTION_URL = "http://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html";
public static final String LAMBDA_PROJECT_DECORATOR_ID = "com.amazonaws.eclipse.lambda.project.lambdaFunctionProjectDecorator";
public static final WebLinkListener webLinkListener = new WebLinkListener();
public static final int MAX_LAMBDA_TAGS = 50;
public static final int MAX_LAMBDA_TAG_KEY_LENGTH = 127;
public static final int MAX_LAMBDA_TAG_VALUE_LENGTH = 255;
}
| 7,863 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/ui/SelectOrInputStackComposite.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.lambda.ui;
import java.util.Arrays;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.widgets.Composite;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase;
import com.amazonaws.eclipse.core.ui.SelectOrInputComposite;
import com.amazonaws.eclipse.lambda.model.SelectOrInputStackDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.page.validator.StackNameValidator;
import com.amazonaws.services.cloudformation.model.StackSummary;
public class SelectOrInputStackComposite extends SelectOrInputComposite<StackSummary, SelectOrInputStackDataModel, AwsResourceScopeParamBase> {
public SelectOrInputStackComposite(
Composite parent,
DataBindingContext bindingContext,
SelectOrInputStackDataModel dataModel) {
super(parent, bindingContext, dataModel,
"Choose an existing Stack:",
"Create a new Stack:",
Arrays.asList(new StackNameValidator()));
}
} | 7,864 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/ui/SelectOrInputFunctionAliasComposite.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.lambda.ui;
import java.util.Arrays;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.widgets.Composite;
import com.amazonaws.eclipse.core.ui.SelectOrInputComposite;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
import com.amazonaws.eclipse.lambda.model.LambdaFunctionAliasesScopeParam;
import com.amazonaws.eclipse.lambda.model.SelectOrInputFunctionAliasDataModel;
import com.amazonaws.services.lambda.model.AliasConfiguration;
public class SelectOrInputFunctionAliasComposite
extends SelectOrInputComposite<AliasConfiguration, SelectOrInputFunctionAliasDataModel, LambdaFunctionAliasesScopeParam> {
public SelectOrInputFunctionAliasComposite(
Composite parent,
DataBindingContext bindingContext,
SelectOrInputFunctionAliasDataModel dataModel) {
super(parent, bindingContext, dataModel,
"Choose an existing function alias:",
"Create a new function alias:",
Arrays.asList(new NotEmptyValidator("Alias name must not be empty")));
}
} | 7,865 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/ui/SelectOrCreateBasicLambdaRoleComposite.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.lambda.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.ui.SelectOrCreateComposite;
import com.amazonaws.eclipse.core.ui.dialogs.AbstractInputDialog;
import com.amazonaws.eclipse.lambda.model.SelectOrCreateBasicLambdaRoleDataModel;
import com.amazonaws.eclipse.lambda.upload.wizard.dialog.CreateBasicLambdaRoleDialog;
import com.amazonaws.services.identitymanagement.model.Role;
public class SelectOrCreateBasicLambdaRoleComposite
extends SelectOrCreateComposite<Role, SelectOrCreateBasicLambdaRoleDataModel, AwsResourceScopeParamBase> {
public SelectOrCreateBasicLambdaRoleComposite(Composite parent, DataBindingContext bindingContext,
SelectOrCreateBasicLambdaRoleDataModel dataModel) {
super(parent, bindingContext, dataModel, "IAM Role:");
}
@Override
protected AbstractInputDialog<Role> createResourceDialog(AwsResourceScopeParamBase param) {
return new CreateBasicLambdaRoleDialog(Display.getCurrent().getActiveShell(), param);
}
}
| 7,866 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/ui/LambdaJavaProjectUtil.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.lambda.ui;
import java.util.Arrays;
import java.util.Set;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
public class LambdaJavaProjectUtil {
// Return the underlying selected JavaElement when performing a command action. Return null if the selected element
// is not Java Element and log the error message.
public static IJavaElement getSelectedJavaElementFromCommandEvent(ExecutionEvent event) {
ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
.getActivePage().getSelection();
if (selection instanceof IStructuredSelection) {
IStructuredSelection structurredSelection = (IStructuredSelection)selection;
Object firstSelection = structurredSelection.getFirstElement();
if (firstSelection instanceof IJavaElement) {
return (IJavaElement) firstSelection;
} else {
LambdaPlugin.getDefault().logInfo(
"Invalid selection: " + firstSelection + " is not Java Element.");
return null;
}
}
return null;
}
// Return the default Java handler FQCN from the selected Java element which must be an ICompilationUnit.
public static String figureOutDefaultLambdaHandler(IJavaElement selectedJavaElement, Set<String> lambdaHandlerSet) {
if (selectedJavaElement instanceof ICompilationUnit) {
ICompilationUnit compilationUnit = (ICompilationUnit)selectedJavaElement;
try {
return Arrays.stream(compilationUnit.getTypes())
.map(IType::getFullyQualifiedName)
.filter(t -> lambdaHandlerSet.contains(t))
.findFirst()
.orElse(null);
} catch (JavaModelException e) {
return null;
}
}
return null;
}
}
| 7,867 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/ui/LambdaPluginColors.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.lambda.ui;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
/**
* Predefined colors to be used by Lambda plugin.
*/
public class LambdaPluginColors {
public static final Color BLACK = new Color(Display.getCurrent(), 0, 0, 0);
public static final Color GREY = new Color(Display.getCurrent(), 214, 214, 214);
} | 7,868 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/ui/SelectOrInputFunctionComposite.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.lambda.ui;
import java.util.Arrays;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.widgets.Composite;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase;
import com.amazonaws.eclipse.core.ui.SelectOrInputComposite;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
import com.amazonaws.eclipse.lambda.model.SelectOrInputFunctionDataModel;
import com.amazonaws.services.lambda.model.FunctionConfiguration;
public class SelectOrInputFunctionComposite
extends SelectOrInputComposite<FunctionConfiguration, SelectOrInputFunctionDataModel, AwsResourceScopeParamBase> {
public SelectOrInputFunctionComposite(
Composite parent,
DataBindingContext bindingContext,
SelectOrInputFunctionDataModel dataModel) {
super(parent, bindingContext, dataModel,
"Choose an existing Lambda function:",
"Create a new Lambda function:",
Arrays.asList(new NotEmptyValidator("Please provide a Lambda name")));
}
}
| 7,869 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/preferences/PreferenceInitializer.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.lambda.preferences;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import com.amazonaws.eclipse.core.util.OsPlatformUtils;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.launching.SamLocalConstants;
public class PreferenceInitializer extends AbstractPreferenceInitializer {
private static final String SAM_LOCAL_WINDOWS_DEFAULT_LOCATION =
String.format("C:\\Users\\%s\\AppData\\Roaming\\npm\\sam.exe", OsPlatformUtils.currentUser());
private static final String SAM_LOCAL_LINUX_DEFAULT_LOCATION = "/usr/local/bin/sam";
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = LambdaPlugin.getDefault().getPreferenceStore();
store.setDefault(SamLocalConstants.P_SAM_LOCAL_EXECUTABLE, getDefaultSamLocalLocation());
}
private String getDefaultSamLocalLocation() {
if (OsPlatformUtils.isWindows()) {
return SAM_LOCAL_WINDOWS_DEFAULT_LOCATION;
} else {
return SAM_LOCAL_LINUX_DEFAULT_LOCATION;
}
}
}
| 7,870 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/preferences/SamLocalPreferencePage.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.lambda.preferences;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import com.amazonaws.eclipse.core.model.ImportFileDataModel;
import com.amazonaws.eclipse.core.ui.ImportFileComposite;
import com.amazonaws.eclipse.core.ui.preferences.AwsToolkitPreferencePage;
import com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory;
import com.amazonaws.eclipse.core.validator.FilePathValidator;
import com.amazonaws.eclipse.lambda.LambdaConstants;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.launching.SamLocalConstants;
public class SamLocalPreferencePage extends AwsToolkitPreferencePage implements IWorkbenchPreferencePage {
private static final String PAGE_NAME = SamLocalPreferencePage.class.getName();
public static final String ID = "com.amazonaws.eclipse.lambda.preferences.SamLocalPreferencePage";
private SamLocalPreferencesDataModel dataModel = new SamLocalPreferencesDataModel();
private DataBindingContext dataBindingContext = new DataBindingContext();
private AggregateValidationStatus aggregateValidationStatus =
new AggregateValidationStatus(dataBindingContext, AggregateValidationStatus.MAX_SEVERITY);
private ImportFileComposite samLocalExecutableComposite;
public SamLocalPreferencePage() {
super(PAGE_NAME);
setDescription("AWS SAM Local Configuration");
this.dispose();
}
@Override
public void init(IWorkbench workbench) {
setPreferenceStore(LambdaPlugin.getDefault().getPreferenceStore());
aggregateValidationStatus.addChangeListener(e -> {
Object value = aggregateValidationStatus.getValue();
if (value instanceof IStatus == false) return;
IStatus status = (IStatus)value;
boolean success = (status.getSeverity() == IStatus.OK);
if (success) {
setErrorMessage(null);
} else {
setErrorMessage(status.getMessage());
}
setValid(success);
});
initDataModel();
}
private void initDataModel() {
dataModel.getSamLocalExecutable().setFilePath(
getPreferenceStore().getString(SamLocalConstants.P_SAM_LOCAL_EXECUTABLE));
}
@Override
protected Control createContents(Composite parent) {
Composite composite = WizardWidgetFactory.newComposite(parent, 1, 1);
WizardWidgetFactory.newLink(
composite,
LambdaConstants.webLinkListener,
"To install AWS SAM Local and the required dependencies, see <a href=\""
+ SamLocalConstants.LINKS_INSTALL_SAM_LOCAL
+ "\">Installation</a>.", 1, 100, 30);
samLocalExecutableComposite = ImportFileComposite.builder(
composite, dataBindingContext, dataModel.getSamLocalExecutable())
.buttonLabel("Browse...")
.filePathValidator(new FilePathValidator("SAM Local Executbale"))
.textLabel("SAM Local Executable:")
.textMessage("Absolute path for sam command...")
.build();
return composite;
}
@Override
protected void performDefaults() {
if (samLocalExecutableComposite != null) {
samLocalExecutableComposite.setFilePath(
getPreferenceStore().getDefaultString(SamLocalConstants.P_SAM_LOCAL_EXECUTABLE));
}
super.performDefaults();
}
@Override
public boolean performOk() {
aggregateValidationStatus.dispose();
dataBindingContext.dispose();
onApplyButton();
return super.performOk();
}
@Override
protected void performApply() {
onApplyButton();
super.performApply();
}
private void onApplyButton() {
String filePath = dataModel.getSamLocalExecutable().getFilePath();
getPreferenceStore().setValue(SamLocalConstants.P_SAM_LOCAL_EXECUTABLE, filePath);
}
private static class SamLocalPreferencesDataModel {
private final ImportFileDataModel samLocalExecutable = new ImportFileDataModel();
public ImportFileDataModel getSamLocalExecutable() {
return samLocalExecutable;
}
}
}
| 7,871 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/Serverless.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.lambda.serverless;
import static com.amazonaws.eclipse.lambda.serverless.model.ResourceType.AWS_SERVERLESS_FUNCTION;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.eclipse.lambda.serverless.model.ServerlessTemplate;
import com.amazonaws.eclipse.lambda.serverless.model.TypeProperties;
import com.amazonaws.eclipse.lambda.serverless.model.transform.ServerlessFunction;
import com.amazonaws.eclipse.lambda.serverless.model.transform.ServerlessModel;
import com.amazonaws.util.IOUtils;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
/**
* A class for processing serverless template file, including loading Serverless template file into a model,
* writing a model back to a Serverless template file, etc.
*/
public class Serverless {
private static final ObjectMapper JSON_MAPPER = initMapper(new ObjectMapper());
private static final ObjectMapper YAML_MAPPER = initMapper(new ObjectMapper(new YAMLFactory()));
private static ObjectMapper initMapper(ObjectMapper mapper) {
mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
return mapper;
}
public static ServerlessModel load(String templatePath) throws JsonParseException, JsonMappingException, IOException {
return load(new File(templatePath));
}
// Load Serverless model from the given template file, and close the input stream safely.
public static ServerlessModel load(File templateFile) throws JsonParseException, JsonMappingException, IOException {
try (InputStream inputStream = new FileInputStream(templateFile)) {
return load(inputStream);
}
}
public static ServerlessModel load(InputStream templateInput) throws JsonParseException, JsonMappingException, IOException {
String content = IOUtils.toString(templateInput);
return loadFromContent(content);
}
public static ServerlessModel loadFromContent(String content) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = isContentInJsonFormat(content) ? JSON_MAPPER : YAML_MAPPER;
ServerlessTemplate serverlessTemplate = mapper.readValue(content.getBytes(StandardCharsets.UTF_8), ServerlessTemplate.class);
return convert(serverlessTemplate);
}
public static File write(ServerlessModel model, String path) throws JsonGenerationException, JsonMappingException, IOException {
File file = new File(path);
ServerlessTemplate template = convert(model);
JSON_MAPPER.writerWithDefaultPrettyPrinter().writeValue(new FileWriter(file), template);
return file;
}
/**
* Return whether the underlying String content is in Json format based on the first non-whitespace character.
*/
private static boolean isContentInJsonFormat(String content) {
if (content == null || content.isEmpty()) {
return false;
}
for (int index = 0; index < content.length(); ++index) {
if (Character.isWhitespace(content.charAt(index))) {
continue;
}
return '{' == content.charAt(index);
}
return false;
}
/**
* Make this raw Serverless model to one that could be recognized by CloudFormation.
*
* @param model - The raw Serverless model.
* @param packagePrefix - The package prefix holding all the Lambda Functions.
* @param filePath - The zipped jar file path. It should be a s3 path since CloudFormation only support this.
* @return A CloudFormation recognized Serverless Model.
*/
public static ServerlessModel cookServerlessModel(ServerlessModel model, String packagePrefix, String filePath) {
for (Entry<String, ServerlessFunction> entry : model.getServerlessFunctions().entrySet()) {
ServerlessFunction function = entry.getValue();
function.setHandler(NameUtils.toHandlerClassFqcn(packagePrefix, function.getHandler()));
function.setCodeUri(filePath);
}
return model;
}
public static ServerlessTemplate convert(ServerlessModel model) {
ServerlessTemplate template = new ServerlessTemplate();
template.setAWSTemplateFormatVersion(model.getAWSTemplateFormatVersion());
template.setDescription(model.getDescription());
template.setTransform(model.getTransform());
for (Entry<String, Object> entry : model.getAdditionalProperties().entrySet()) {
template.addAdditionalProperty(entry.getKey(), entry.getValue());
}
for (Entry<String, TypeProperties> entry : model.getAdditionalResources().entrySet()) {
template.addResource(entry.getKey(), entry.getValue());
}
// Put Serverless resources to the map.
for (Entry<String, ServerlessFunction> entry : model.getServerlessFunctions().entrySet()) {
String resourceLogicalId = entry.getKey();
ServerlessFunction serverlessFunction = entry.getValue();
template.addResource(resourceLogicalId, serverlessFunction.toTypeProperties());
}
return template;
}
private static ServerlessModel convert(ServerlessTemplate template) {
ServerlessModel model = new ServerlessModel();
model.setAWSTemplateFormatVersion(template.getAWSTemplateFormatVersion());
model.setDescription(template.getDescription());
model.setTransform(template.getTransform());
for (Entry<String, Object> entry : template.getAdditionalProperties().entrySet()) {
model.addAdditionalProperty(entry.getKey(), entry.getValue());
}
for (Entry<String, TypeProperties> entry : template.getResources().entrySet()) {
String key = entry.getKey();
TypeProperties resource = entry.getValue();
convertResource(model, key, resource);
}
return model;
}
/**
* Convert a general representation of a resource to a modeled resource and put it to ServerlessModel.
*
* @param model The Serverless model in which the converted resource will be put.
* @param resourceLogicalId The logical id for the resource.
* @param resource The general representation for the resource.
*/
private static void convertResource(ServerlessModel model, String resourceLogicalId, TypeProperties resource) {
String type = resource.getType();
if (AWS_SERVERLESS_FUNCTION.getType().equals(type)) {
ServerlessFunction function = convertServerlessFunction(resource);
model.addServerlessFunction(resourceLogicalId, function);
} else {
// Unrecognized resources put to additionalResources
model.addAdditionalResource(resourceLogicalId, resource);
}
}
private static ServerlessFunction convertServerlessFunction(TypeProperties tp) {
Map<String, Object> resource = tp.getProperties();
ServerlessFunction function = JSON_MAPPER.convertValue(resource, ServerlessFunction.class);
for (Entry<String, Object> entry : tp.getAdditionalProperties().entrySet()) {
function.addAdditionalTopLevelProperty(entry.getKey(), entry.getValue());
}
return function;
}
private static Map<String, TypeProperties> convert(Map<String, Object> map) {
Map<String, TypeProperties> typeProperties = new HashMap<>();
for (Entry<String, Object> entry : map.entrySet()) {
typeProperties.put(entry.getKey(), JSON_MAPPER.convertValue(entry.getValue(), TypeProperties.class));
}
return typeProperties;
}
}
| 7,872 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/NameUtils.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.lambda.serverless;
import com.amazonaws.util.StringUtils;
public class NameUtils {
public static final String SERVERLESS_GENERATED_TEMPLATE_FILE_NAME = "serverless.generated.template";
public static final String SERVERLESS_INPUT_CLASS_NAME = "ServerlessInput";
public static final String SERVERLESS_OUTPUT_CLASS_NAME = "ServerlessOutput";
/*
* Transform the handler name (may or may not be the FQCN) to the class name.
*/
public static String toHandlerClassName(String handlerName) {
return capitalizeWord(handlerName.substring(handlerName.lastIndexOf(".") + 1));
}
public static String toModelClassName(String modelName) {
return capitalizeWord(modelName);
}
public static String toHandlerPackageName(String packagePrefix) {
return packagePrefix + ".function";
}
public static String toModelPackageName(String packagePrefix) {
return packagePrefix + ".model";
}
// Replace handlerName with it's FQCN: if the handlerName is already FQCN or no package prefix
// is specified, return itself.
public static String toHandlerClassFqcn(String packagePrefix, String handlerName) {
int lastIndexOfDot = handlerName.lastIndexOf('.');
if (lastIndexOfDot != -1 || StringUtils.isNullOrEmpty(packagePrefix)) {
return handlerName;
}
return toHandlerPackageName(packagePrefix) + "." + handlerName;
}
public static String toServerlessInputModelFqcn(String packagePrefix) {
return toModelPackageName(packagePrefix) + "." + SERVERLESS_INPUT_CLASS_NAME;
}
public static String toServerlessOutputModelFqcn(String packagePrefix) {
return toModelPackageName(packagePrefix) + "." + SERVERLESS_OUTPUT_CLASS_NAME;
}
public static String toRequestClassName(String operationName) {
return toHandlerClassName(operationName) + "Request";
}
public static String toResponseClassName(String operationName) {
return toHandlerClassName(operationName) + "Response";
}
public static String toRequestClassFqcn(String packagePrefix,
String operationName) {
return toModelPackageName(packagePrefix) + "."
+ toRequestClassName(operationName);
}
public static String toResponseClassFqcn(String packagePrefix,
String operationName) {
return toModelPackageName(packagePrefix) + "."
+ toResponseClassName(operationName);
}
private static String capitalizeWord(String word) {
return word.substring(0, 1).toUpperCase() + word.substring(1);
}
} | 7,873 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/handler/DeployServerlessProjectHandler.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.lambda.serverless.handler;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
import com.amazonaws.eclipse.core.util.WorkbenchUtils;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil;
import com.amazonaws.eclipse.lambda.serverless.wizard.DeployServerlessProjectWizard;
import com.amazonaws.eclipse.lambda.upload.wizard.util.UploadFunctionUtil;
public class DeployServerlessProjectHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
.getActivePage().getSelection();
if (selection instanceof IStructuredSelection) {
IStructuredSelection structurredSelection = (IStructuredSelection)selection;
Object firstSeleciton = structurredSelection.getFirstElement();
IProject selectedProject = null;
if (firstSeleciton instanceof IProject) {
selectedProject = (IProject) firstSeleciton;
} else if (firstSeleciton instanceof IJavaProject) {
selectedProject = ((IJavaProject) firstSeleciton).getProject();
} else {
LambdaPlugin.getDefault().logInfo(
"Invalid selection: " + firstSeleciton + " is not a Serverless project.");
return null;
}
doDeployServerlessTemplate(selectedProject);
}
return null;
}
public static void doDeployServerlessTemplate(IProject project) {
if (!WorkbenchUtils.openSaveFilesDialog(PlatformUI.getWorkbench())) {
return;
}
Set<String> handlerClasses = new HashSet<>(UploadFunctionUtil.findValidHandlerClass(project));
handlerClasses.addAll(UploadFunctionUtil.findValidStreamHandlerClass(project));
if (handlerClasses.isEmpty()) {
MessageDialog.openError(
Display.getCurrent().getActiveShell(),
"Invalid AWS Lambda Project",
"No Lambda function handler class is found in the project. " +
"You need to have at least one concrete class that implements the " +
"com.amazonaws.services.lambda.runtime.RequestHandler interface.");
return;
}
File serverlessTemplate = FunctionProjectUtil.getServerlessTemplateFile(project);
if (!serverlessTemplate.exists() || !serverlessTemplate.isFile()) {
MessageDialog.openError(
Display.getCurrent().getActiveShell(),
"Invalid AWS Serverless Project",
"No serverless.template file found in your project root.");
return;
}
WizardDialog wizardDialog = new WizardDialog(
Display.getCurrent().getActiveShell(),
new DeployServerlessProjectWizard(project, handlerClasses));
wizardDialog.open();
}
}
| 7,874 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/handler/SamLocalHandler.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.lambda.serverless.handler;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jdt.core.IJavaElement;
import com.amazonaws.eclipse.lambda.launching.SamLocalExecution;
import com.amazonaws.eclipse.lambda.launching.SamLocalExecution.LaunchMode;
import com.amazonaws.eclipse.lambda.ui.LambdaJavaProjectUtil;
/**
* Action of running/debugging SAM application when right clicking project explorer.
*/
public class SamLocalHandler {
public static class RunSamLocalHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IJavaElement selectedJavaElement = LambdaJavaProjectUtil.getSelectedJavaElementFromCommandEvent(event);
SamLocalExecution.launch(selectedJavaElement, LaunchMode.RUN);
return null;
}
}
public static class DebugSamLocalHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IJavaElement selectedJavaElement = LambdaJavaProjectUtil.getSelectedJavaElementFromCommandEvent(event);
SamLocalExecution.launch(selectedJavaElement, LaunchMode.DEBUG);
return null;
}
}
} | 7,875 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/ui/DeployServerlessProjectPageTwo.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.lambda.serverless.ui;
import java.io.File;
import java.io.IOException;
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.core.runtime.Status;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import com.amazonaws.eclipse.cloudformation.model.ParametersDataModel;
import com.amazonaws.eclipse.cloudformation.ui.ParametersComposite;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.project.wizard.model.DeployServerlessProjectDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.DescribeStacksRequest;
import com.amazonaws.services.cloudformation.model.DescribeStacksResult;
import com.amazonaws.services.cloudformation.model.Parameter;
import com.amazonaws.services.cloudformation.model.Stack;
import com.amazonaws.services.cloudformation.model.TemplateParameter;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DeployServerlessProjectPageTwo extends WizardPage {
private final DeployServerlessProjectDataModel dataModel;
private DataBindingContext bindingContext;
private AggregateValidationStatus aggregateValidationStatus;
private static final String OK_MESSAGE = "Provide values for template parameters.";
private Composite comp;
private ScrolledComposite scrolledComp;
public DeployServerlessProjectPageTwo(DeployServerlessProjectDataModel dataModel) {
super("Fill in stack template parameters");
setTitle("Fill in stack template parameters");
setDescription(OK_MESSAGE);
this.dataModel = dataModel;
initDataModel();
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets
* .Composite)
*/
@Override
public void createControl(final Composite parent) {
scrolledComp = new ScrolledComposite(parent, SWT.V_SCROLL);
scrolledComp.setExpandHorizontal(true);
scrolledComp.setExpandVertical(true);
GridDataFactory.fillDefaults().grab(true, true).applyTo(scrolledComp);
comp = new Composite(scrolledComp, SWT.None);
GridDataFactory.fillDefaults().grab(true, true).applyTo(comp);
GridLayoutFactory.fillDefaults().numColumns(1).applyTo(comp);
scrolledComp.setContent(comp);
scrolledComp.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
if (comp != null) {
Rectangle r = scrolledComp.getClientArea();
scrolledComp.setMinSize(comp.computeSize(r.width, SWT.DEFAULT));
}
}
});
setControl(scrolledComp);
}
// Fill in previous parameters from the existing stack
private void fillinParameters() {
AmazonCloudFormation cloudFormation = AwsToolkitCore.getClientFactory().getCloudFormationClientByRegion(
dataModel.getRegionDataModel().getRegion().getId());
if (dataModel.getStackDataModel().isSelectExistingResource()) {
DescribeStacksResult describeStacks = cloudFormation.describeStacks(new DescribeStacksRequest()
.withStackName(dataModel.getStackDataModel().getStackName()));
Stack existingStack = null;
if ( describeStacks.getStacks().size() == 1 ) {
existingStack = describeStacks.getStacks().get(0);
}
if (existingStack != null) {
for ( Parameter param : existingStack.getParameters() ) {
boolean noEcho = false;
// This is a pain, but any "noEcho" parameters get returned as asterisks in the service response.
// The customer must fill these values out again, even for a running stack.
for ( TemplateParameter templateParam : dataModel.getParametersDataModel().getTemplateParameters()) {
if (templateParam.getNoEcho() && templateParam.getParameterKey().equals(param.getParameterKey())) {
noEcho = true;
break;
}
}
if ( !noEcho ) {
dataModel.getParametersDataModel().getParameterValues().put(
param.getParameterKey(), param.getParameterValue());
}
}
}
}
}
private void createContents() {
for ( Control c : comp.getChildren() ) {
c.dispose();
}
bindingContext = new DataBindingContext();
aggregateValidationStatus = new AggregateValidationStatus(bindingContext,
AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
populateValidationStatus();
}
});
new ParametersComposite(comp, dataModel.getParametersDataModel(), bindingContext);
comp.layout();
Rectangle r = scrolledComp.getClientArea();
scrolledComp.setMinSize(comp.computeSize(r.width, SWT.DEFAULT));
}
@Override
public void setVisible(boolean visible) {
if ( visible ) {
fillinParameters();
createContents();
}
super.setVisible(visible);
}
private void initDataModel() {
try {
ParametersDataModel parametersDataModel = dataModel.getParametersDataModel();
File serverlessTemplate = FunctionProjectUtil.getServerlessTemplateFile(dataModel.getProject());
ObjectMapper mapper = new ObjectMapper();
Map templateModel = mapper.readValue(serverlessTemplate, Map.class);
parametersDataModel.setTemplate(templateModel);
} catch (IOException e) {
LambdaPlugin.getDefault().reportException(e.getMessage(), e);
}
}
private void populateValidationStatus() {
Object value = aggregateValidationStatus.getValue();
if ( value instanceof IStatus == false )
return;
IStatus status = (IStatus) value;
if ( status.isOK() ) {
setErrorMessage(null);
setMessage(OK_MESSAGE, Status.OK);
} else if ( status.getSeverity() == Status.WARNING ) {
setErrorMessage(null);
setMessage(status.getMessage(), Status.WARNING);
} else if ( status.getSeverity() == Status.ERROR ) {
setErrorMessage(status.getMessage());
}
setPageComplete(status.isOK());
}
}
| 7,876 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/ui/FormBrowser.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.lambda.serverless.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledFormText;
public class FormBrowser {
FormToolkit toolkit;
Composite container;
ScrolledFormText formText;
String text;
int style;
public FormBrowser(int style) {
this.style = style;
}
public void createControl(Composite parent) {
toolkit = new FormToolkit(parent.getDisplay());
int borderStyle = toolkit.getBorderStyle() == SWT.BORDER ? SWT.NULL : SWT.BORDER;
container = new Composite(parent, borderStyle);
FillLayout flayout = new FillLayout();
flayout.marginWidth = 1;
flayout.marginHeight = 1;
container.setLayout(flayout);
formText = new ScrolledFormText(container, SWT.V_SCROLL | SWT.H_SCROLL, false);
if (borderStyle == SWT.NULL) {
formText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER);
toolkit.paintBordersFor(container);
}
FormText ftext = toolkit.createFormText(formText, false);
formText.setFormText(ftext);
formText.setExpandHorizontal(true);
formText.setExpandVertical(true);
formText.setBackground(toolkit.getColors().getBackground());
formText.setForeground(toolkit.getColors().getForeground());
ftext.marginWidth = 2;
ftext.marginHeight = 2;
ftext.setHyperlinkSettings(toolkit.getHyperlinkGroup());
formText.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
if (toolkit != null) {
toolkit.dispose();
toolkit = null;
}
}
});
if (text != null)
formText.setText(text);
}
public Control getControl() {
return container;
}
public void setText(String text) {
this.text = text;
if (formText != null)
formText.setText(text);
}
} | 7,877 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/ui/DeployServerlessProjectPage.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.lambda.serverless.ui;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLink;
import static com.amazonaws.eclipse.lambda.LambdaAnalytics.trackRegionComboChangeSelection;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import org.apache.commons.io.IOUtils;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.ChangeEvent;
import org.eclipse.core.databinding.observable.IChangeListener;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.observable.value.WritableValue;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.core.ui.CancelableThread;
import com.amazonaws.eclipse.core.ui.MultipleSelectionListComposite;
import com.amazonaws.eclipse.core.ui.RegionComposite;
import com.amazonaws.eclipse.core.ui.SelectOrCreateBucketComposite;
import com.amazonaws.eclipse.core.util.S3BucketUtil;
import com.amazonaws.eclipse.databinding.ChainValidator;
import com.amazonaws.eclipse.lambda.LambdaConstants;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.model.SelectOrInputStackDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.model.DeployServerlessProjectDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil;
import com.amazonaws.eclipse.lambda.serverless.Serverless;
import com.amazonaws.eclipse.lambda.serverless.model.transform.ServerlessFunction;
import com.amazonaws.eclipse.lambda.serverless.model.transform.ServerlessModel;
import com.amazonaws.eclipse.lambda.ui.SelectOrInputStackComposite;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.Capability;
import com.amazonaws.services.cloudformation.model.TemplateParameter;
import com.amazonaws.services.cloudformation.model.ValidateTemplateRequest;
public class DeployServerlessProjectPage extends WizardPage {
private static final String VALIDATING = "validating";
private static final String INVALID = "invalid";
private static final String VALID = "valid";
private final DeployServerlessProjectDataModel dataModel;
private final DataBindingContext bindingContext;
private final AggregateValidationStatus aggregateValidationStatus;
private RegionComposite regionComposite;
private SelectOrCreateBucketComposite bucketComposite;
private SelectOrInputStackComposite stackComposite;
private MultipleSelectionListComposite<Capability> capabilitiesSelectionComposite;
private IObservableValue templateValidated = new WritableValue();
private ValidateTemplateThread validateTemplateThread;
private Exception templateValidationException;
public DeployServerlessProjectPage(DeployServerlessProjectDataModel dataModel) {
super("ServerlessDeployWizardPage");
setTitle("Deploy Serverless stack to AWS CloudFormation.");
setDescription("Deploy your Serverless template to AWS CloudFormation as a stack.");
this.dataModel = dataModel;
this.bindingContext = new DataBindingContext();
this.aggregateValidationStatus = new AggregateValidationStatus(
bindingContext, AggregateValidationStatus.MAX_SEVERITY);
}
@Override
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new GridLayout(1, false));
createRegionSection(container);
createS3BucketSection(container);
createStackSection(container);
createCapabilities(container);
createValidationBinding();
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent arg0) {
populateHandlerValidationStatus();
}
});
dataModel.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// We skip this event for inputing a new Stack name. We only listener to changes of Bucket, Existing Stack
if (!evt.getPropertyName().equals(SelectOrInputStackDataModel.P_NEW_RESOURCE_NAME)) {
onDataModelPropertiesChange();
}
}
});
onRegionSelectionChange();
setControl(container);
}
private void populateHandlerValidationStatus() {
if (aggregateValidationStatus == null) {
return;
}
Object value = aggregateValidationStatus.getValue();
if (! (value instanceof IStatus)) return;
IStatus handlerInfoStatus = (IStatus) value;
boolean isHandlerInfoValid = (handlerInfoStatus.getSeverity() == IStatus.OK);
if (isHandlerInfoValid) {
setErrorMessage(null);
super.setPageComplete(true);
} else {
setErrorMessage(handlerInfoStatus.getMessage());
super.setPageComplete(false);
}
}
private void createRegionSection(Composite parent) {
Group regionGroup = newGroup(parent, "Select AWS Region for the AWS CloudFormation stack");
regionGroup.setLayout(new GridLayout(1, false));
regionComposite = RegionComposite.builder()
.parent(regionGroup)
.bindingContext(bindingContext)
.serviceName(ServiceAbbreviations.CLOUD_FORMATION)
.dataModel(dataModel.getRegionDataModel())
.labelValue("Select AWS Region:")
.addListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
trackRegionComboChangeSelection();
onRegionSelectionChange();
}
})
.build();
}
private void onRegionSelectionChange() {
Region currentSelectedRegion = regionComposite.getCurrentSelectedRegion();
if (bucketComposite != null) {
String defaultBucket = dataModel.getMetadata().getLastDeploymentBucket(currentSelectedRegion.getId());
bucketComposite.refreshComposite(new AwsResourceScopeParamBase(
AwsToolkitCore.getDefault().getCurrentAccountId(),
currentSelectedRegion.getId()), defaultBucket);
}
if (stackComposite != null) {
String defaultStackName = dataModel.getMetadata().getLastDeploymentStack(currentSelectedRegion.getId());
stackComposite.refreshComposite(new AwsResourceScopeParamBase(
AwsToolkitCore.getDefault().getCurrentAccountId(),
currentSelectedRegion.getId()), defaultStackName);
}
}
private void createS3BucketSection(Composite parent) {
Group group = newGroup(parent, "Select or Create S3 Bucket for Your Function Code");
group.setLayout(new GridLayout(1, false));
bucketComposite = new SelectOrCreateBucketComposite(
group, bindingContext, dataModel.getBucketDataModel());
}
private void createStackSection(Composite parent) {
Group group = newGroup(parent, "Select or Create CloudFormation Stack");
group.setLayout(new GridLayout(1, false));
stackComposite = new SelectOrInputStackComposite(
group, bindingContext, dataModel.getStackDataModel());
}
private void createCapabilities(Composite parent) {
Group group = newGroup(parent, "Configure capabilities");
group.setLayout(new GridLayout(1, false));
newLink(group,
LambdaConstants.webLinkListener,
"If you have IAM resources, you can specify either capability. If you " +
"have IAM resources with custom names, you must specify CAPABILITY_NAMED_IAM. " +
"You must select at least one capability. " +
"For more information, see <a href=\"" +
LambdaConstants.CLOUDFORMATION_CAPABILITIES +
"\">Acknowledging IAM Resources in AWS CloudFormation Templates</a>.", 1, 100, 50);
capabilitiesSelectionComposite = new MultipleSelectionListComposite<>(
group, bindingContext, dataModel.getCapabilitiesDataModel(),
Arrays.asList(Capability.values()),
Arrays.asList(Capability.CAPABILITY_IAM),
"You must select at least one capability");
}
private void createValidationBinding() {
templateValidated.setValue(null);
bindingContext.addValidationStatusProvider(new ChainValidator<String>(templateValidated, new IValidator() {
@Override
public IStatus validate(Object value) {
if ( value == null ) {
return ValidationStatus.error("No template selected");
}
if ( ((String) value).equals(VALID) ) {
return ValidationStatus.ok();
} else if ( ((String) value).equals(VALIDATING) ) {
return ValidationStatus.warning("Validating template...");
} else if ( ((String) value).equals(INVALID) ) {
if ( templateValidationException != null ) {
return ValidationStatus.error("Invalid template: " + templateValidationException.getMessage());
} else {
return ValidationStatus.error("No template selected");
}
}
return ValidationStatus.ok();
}
}));
}
private void onDataModelPropertiesChange() {
CancelableThread.cancelThread(validateTemplateThread);
validateTemplateThread = new ValidateTemplateThread();
validateTemplateThread.start();
}
// The IObservable value could only be updated in the UI thread.
private void updateTemplateValidatedStatus(final CancelableThread motherThread, final String newStatus) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
synchronized (motherThread) {
if (!motherThread.isCanceled()) {
templateValidated.setValue(newStatus);
}
}
}
});
}
/**
* Cancelable thread to validate a template and update the validation
* status.
*/
private final class ValidateTemplateThread extends CancelableThread {
@Override
public void run() {
try {
updateTemplateValidatedStatus(this, VALIDATING);
// Update serverless template upon provided bucket name
String lambdaFunctionJarFileKeyName = dataModel.getStackDataModel().getStackName() + "-" + System.currentTimeMillis() + ".zip";
File serverlessTemplateFile = FunctionProjectUtil.getServerlessTemplateFile(dataModel.getProject());
ServerlessModel model = Serverless.load(serverlessTemplateFile);
model = Serverless.cookServerlessModel(model, dataModel.getMetadata().getPackagePrefix(),
S3BucketUtil.createS3Path(dataModel.getBucketDataModel().getBucketName(), lambdaFunctionJarFileKeyName));
validateHandlersExist(model);
String generatedServerlessFilePath = File.createTempFile(
"serverless-template", ".json").getAbsolutePath();
File serverlessGeneratedTemplateFile = Serverless.write(model, generatedServerlessFilePath);
serverlessGeneratedTemplateFile.deleteOnExit();
dataModel.setLambdaFunctionJarFileKeyName(lambdaFunctionJarFileKeyName);
dataModel.setUpdatedServerlessTemplate(serverlessGeneratedTemplateFile);
// Validate the updated serverless template
AmazonCloudFormation cloudFormation = AwsToolkitCore.getClientFactory().getCloudFormationClientByRegion(
dataModel.getRegionDataModel().getRegion().getId());
List<TemplateParameter> templateParameters = cloudFormation.validateTemplate(new ValidateTemplateRequest()
.withTemplateBody(IOUtils.toString(new FileInputStream(serverlessGeneratedTemplateFile))))
.getParameters();
dataModel.getParametersDataModel().setTemplateParameters(templateParameters);
updateTemplateValidatedStatus(this, VALID);
} catch (Exception e) {
templateValidationException = e;
updateTemplateValidatedStatus(this, INVALID);
LambdaPlugin.getDefault().logError(e.getMessage(), e);
}
}
// Validate the Lambda handlers defined in the serverless template exist in the project.
private void validateHandlersExist(ServerlessModel model) {
for (Entry<String, ServerlessFunction> handler : model.getServerlessFunctions().entrySet()) {
if (!dataModel.getHandlerClasses().contains(handler.getValue().getHandler())) {
throw new IllegalArgumentException(String.format(
"The configured handler class %s for Lambda handler %s doesn't exist!",
handler.getValue().getHandler(), handler.getKey()));
}
}
}
}
}
| 7,878 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/validator/ServerlessTemplateFilePathValidator.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.lambda.serverless.validator;
import java.io.IOException;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import com.amazonaws.eclipse.core.util.PluginUtils;
import com.amazonaws.eclipse.lambda.serverless.Serverless;
import com.amazonaws.eclipse.lambda.serverless.model.transform.ServerlessModel;
import com.amazonaws.util.StringUtils;
public class ServerlessTemplateFilePathValidator implements IValidator {
@Override
public IStatus validate(Object value) {
String filePath = (String) value;
try {
validateFilePath(filePath);
} catch (Exception e) {
return ValidationStatus.error(e.getMessage());
}
return ValidationStatus.ok();
}
public ServerlessModel validateFilePath(String filePath) {
if (StringUtils.isNullOrEmpty(filePath)) {
throw new IllegalArgumentException("Serverless template file path must be provided!");
}
try {
filePath = PluginUtils.variablePluginReplace(filePath);
ServerlessModel model = Serverless.load(filePath);
if (model.getAdditionalResources().isEmpty() && model.getServerlessFunctions().isEmpty()) {
throw new IllegalArgumentException("Serverless template file is not valid, you need to define at least one AWS Resource.");
}
return model;
} catch (IOException | CoreException e) {
throw new IllegalArgumentException(e);
}
}
} | 7,879 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/wizard/DeployServerlessProjectWizard.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.lambda.serverless.wizard;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.plugin.AbstractAwsJobWizard;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.explorer.cloudformation.OpenStackEditorAction;
import com.amazonaws.eclipse.lambda.LambdaAnalytics;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.project.metadata.ProjectMetadataManager;
import com.amazonaws.eclipse.lambda.project.metadata.ServerlessProjectMetadata;
import com.amazonaws.eclipse.lambda.project.wizard.model.DeployServerlessProjectDataModel;
import com.amazonaws.eclipse.lambda.serverless.ui.DeployServerlessProjectPage;
import com.amazonaws.eclipse.lambda.serverless.ui.DeployServerlessProjectPageTwo;
import com.amazonaws.eclipse.lambda.upload.wizard.util.FunctionJarExportHelper;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.AmazonCloudFormationException;
import com.amazonaws.services.cloudformation.model.Capability;
import com.amazonaws.services.cloudformation.model.ChangeSetStatus;
import com.amazonaws.services.cloudformation.model.ChangeSetType;
import com.amazonaws.services.cloudformation.model.CreateChangeSetRequest;
import com.amazonaws.services.cloudformation.model.DeleteChangeSetRequest;
import com.amazonaws.services.cloudformation.model.DeleteStackRequest;
import com.amazonaws.services.cloudformation.model.DescribeChangeSetRequest;
import com.amazonaws.services.cloudformation.model.DescribeChangeSetResult;
import com.amazonaws.services.cloudformation.model.DescribeStacksRequest;
import com.amazonaws.services.cloudformation.model.ExecuteChangeSetRequest;
import com.amazonaws.services.cloudformation.model.ListStacksRequest;
import com.amazonaws.services.cloudformation.model.ListStacksResult;
import com.amazonaws.services.cloudformation.model.Parameter;
import com.amazonaws.services.cloudformation.model.Stack;
import com.amazonaws.services.cloudformation.model.StackStatus;
import com.amazonaws.services.cloudformation.model.StackSummary;
import com.amazonaws.services.cloudformation.model.Tag;
import com.amazonaws.services.cloudformation.model.TemplateParameter;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import com.amazonaws.util.StringUtils;
public class DeployServerlessProjectWizard extends AbstractAwsJobWizard {
// AWS CloudFormation stack statuses for updating the ChangeSet.
private static final Set<String> STATUSES_FOR_UPDATE = new HashSet<>(Arrays.asList(
StackStatus.CREATE_COMPLETE.toString(),
StackStatus.UPDATE_COMPLETE.toString(),
StackStatus.UPDATE_ROLLBACK_COMPLETE.toString()));
// AWS CloudFormation stack statuses for creating a new ChangeSet.
private static final Set<String> STATUSES_FOR_CREATE = new HashSet<>(Arrays.asList(
StackStatus.REVIEW_IN_PROGRESS.toString(),
StackStatus.DELETE_COMPLETE.toString()));
// AWS CloudFormation stack statuses for waiting and deleting the stack first, then creating a new ChangeSet.
private static final Set<String> STATUSES_FOR_DELETE = new HashSet<>(Arrays.asList(
StackStatus.ROLLBACK_IN_PROGRESS.toString(),
StackStatus.ROLLBACK_COMPLETE.toString(),
StackStatus.DELETE_IN_PROGRESS.toString()));
private DeployServerlessProjectDataModel dataModel;
public DeployServerlessProjectWizard(IProject project, Set<String> handlerClasses) {
super("Deploy Serverless application to AWS");
this.dataModel = new DeployServerlessProjectDataModel(project, handlerClasses);
initDataModel();
}
@Override
public void addPages() {
addPage(new DeployServerlessProjectPage(dataModel));
addPage(new DeployServerlessProjectPageTwo(dataModel));
}
@Override
public IStatus doFinish(IProgressMonitor monitor) {
monitor.beginTask("Deploying Serverless template to AWS CloudFormation.", 100);
try {
if (deployServerlessTemplate(monitor, 100)) {
new OpenStackEditorAction(
dataModel.getStackDataModel().getStackName(), dataModel.getRegionDataModel().getRegion(), true).run();
} else {
return Status.CANCEL_STATUS;
}
} catch (Exception e) {
LambdaPlugin.getDefault().reportException(
"Failed to deploy serverless project to AWS CloudFormation.", e);
LambdaAnalytics.trackDeployServerlessProjectFailed();
return new Status(Status.ERROR, LambdaPlugin.PLUGIN_ID,
"Failed to deploy serverless project to AWS CloudFormation.", e);
}
monitor.done();
LambdaAnalytics.trackDeployServerlessProjectSucceeded();
return Status.OK_STATUS;
}
@Override
protected String getJobTitle() {
return "Deploying Serverless template to AWS CloudFormation.";
}
@Override
public boolean performCancel() {
LambdaAnalytics.trackServerlessProjectCreationCanceled();
return true;
}
private boolean deployServerlessTemplate(IProgressMonitor monitor, int totalUnitOfWork) throws IOException, InterruptedException {
String stackName = dataModel.getStackDataModel().getStackName();
monitor.subTask("Exporting Lambda functions...");
File jarFile = FunctionJarExportHelper.exportProjectToJarFile(dataModel.getProject(), true);
monitor.worked((int)(totalUnitOfWork * 0.1));
if (monitor.isCanceled()) {
return false;
}
Region region = dataModel.getRegionDataModel().getRegion();
String bucketName = dataModel.getBucketDataModel().getBucketName();
AmazonS3 s3 = AwsToolkitCore.getClientFactory().getS3ClientByRegion(region.getId());
TransferManager tm = TransferManagerBuilder.standard()
.withS3Client(s3)
.build();
monitor.subTask("Uploading Lambda function to S3...");
LambdaAnalytics.trackExportedJarSize(jarFile.length());
long startTime = System.currentTimeMillis();
Upload upload = tm.upload(new PutObjectRequest(bucketName, dataModel.getLambdaFunctionJarFileKeyName(), jarFile));
while (!upload.isDone() && !monitor.isCanceled()) {
Thread.sleep(500L); // Sleep for half a second
}
if (upload.isDone()) {
long uploadTime = System.currentTimeMillis() - startTime;
LambdaAnalytics.trackUploadS3BucketTime(uploadTime);
LambdaAnalytics.trackUploadS3BucketSpeed((double) jarFile.length()
/ (double) uploadTime);
monitor.worked((int) (totalUnitOfWork * 0.4));
} else if (monitor.isCanceled()) {
upload.abort(); // Abort the uploading and return
return false;
}
monitor.subTask("Uploading Generated Serverless template to S3...");
String generatedServerlessTemplateKeyName = stackName + "-" + System.currentTimeMillis() + ".template";
s3.putObject(bucketName, generatedServerlessTemplateKeyName, dataModel.getUpdatedServerlessTemplate());
monitor.worked((int)(totalUnitOfWork * 0.1));
if (monitor.isCanceled()) {
return false;
}
AmazonCloudFormation cloudFormation = AwsToolkitCore.getClientFactory().getCloudFormationClientByRegion(region.getId());
monitor.subTask("Creating ChangeSet...");
String changeSetName = stackName + "-changeset-" + System.currentTimeMillis();
ChangeSetType changeSetType = ChangeSetType.CREATE;
StackSummary stackSummary = getCloudFormationStackSummary(cloudFormation, stackName);
Stack stack = stackSummary == null ? null : getCloudFormationStackById(cloudFormation, stackSummary.getStackId());
if (stack == null || STATUSES_FOR_CREATE.contains(stack.getStackStatus())) {
changeSetType = ChangeSetType.CREATE;
} else if (STATUSES_FOR_DELETE.contains(stack.getStackStatus())) {
String stackId = stack.getStackId();
if (stack.getStackStatus().equals(StackStatus.ROLLBACK_IN_PROGRESS.toString())) {
stack = waitStackForRollbackComplete(cloudFormation, stackId);
}
if (stack != null && stack.getStackStatus().equals(StackStatus.ROLLBACK_COMPLETE.toString())) {
cloudFormation.deleteStack(new DeleteStackRequest().withStackName(stackName));
waitStackForDeleteComplete(cloudFormation, stackId);
}
if (stack != null && stack.getStackStatus().equals(StackStatus.DELETE_IN_PROGRESS.toString())) {
waitStackForDeleteComplete(cloudFormation, stackId);
}
changeSetType = ChangeSetType.CREATE;
} else if (STATUSES_FOR_UPDATE.contains(stack.getStackStatus())) {
changeSetType = ChangeSetType.UPDATE;
} else {
String errorMessage = String.format("The stack's current state of %s is invalid for updating", stack.getStackStatus());
LambdaPlugin.getDefault().logError(errorMessage, null);
throw new RuntimeException(errorMessage);
}
cloudFormation.createChangeSet(new CreateChangeSetRequest()
.withTemplateURL(s3.getUrl(bucketName, generatedServerlessTemplateKeyName).toString())
.withChangeSetName(changeSetName).withStackName(stackName)
.withChangeSetType(changeSetType)
.withCapabilities(dataModel.getCapabilitiesDataModel().getSelectedList().toArray(new Capability[0]))
.withParameters(dataModel.getParametersDataModel().getParameters())
.withTags(new Tag().withKey("ApiGateway").withValue("true")));
waitChangeSetCreateComplete(cloudFormation, stackName, changeSetName);
if (monitor.isCanceled()) {
cloudFormation.deleteChangeSet(new DeleteChangeSetRequest().withChangeSetName(changeSetName).withStackName(stackName));
return false;
} else {
monitor.worked((int)(totalUnitOfWork * 0.2));
}
monitor.subTask("Executing ChangeSet...");
cloudFormation.executeChangeSet(new ExecuteChangeSetRequest()
.withChangeSetName(changeSetName).withStackName(stackName));
monitor.worked((int)(totalUnitOfWork * 0.2));
return true;
}
/**
* We use {@link AmazonCloudFormation#listStacks(ListStacksRequest)} instead of {@link AmazonCloudFormation#describeStacks(DescribeStacksRequest)}}
* because describeStacks API doesn't return deleted Stacks.
*/
private StackSummary getCloudFormationStackSummary(AmazonCloudFormation client, String stackName) {
String nextToken = null;
do {
ListStacksResult result = client.listStacks(new ListStacksRequest().withNextToken(nextToken));
nextToken = result.getNextToken();
for (StackSummary summary : result.getStackSummaries()) {
if (summary.getStackName().equals(stackName)) {
return summary;
}
}
} while (nextToken != null);
return null;
}
/**
* Get stack by ID. Note: the parameter must be stack id other than stack name to return the deleted stacks.
*/
private Stack getCloudFormationStackById(AmazonCloudFormation client, String stackId) {
try {
List<Stack> stacks = client.describeStacks(new DescribeStacksRequest().withStackName(stackId)).getStacks();
return stacks.isEmpty() ? null : stacks.get(0);
} catch (AmazonCloudFormationException e) {
// AmazonCloudFormation throws exception if the specified stack doesn't exist.
return null;
}
}
private Stack waitStackForNoLongerInProgress(AmazonCloudFormation client, String stackId) {
try {
Stack currentStack;
do {
Thread.sleep(3000L); // check every 3 seconds
currentStack = getCloudFormationStackById(client, stackId);
} while (currentStack != null && currentStack.getStackStatus().endsWith("IN_PROGRESS"));
return currentStack;
} catch (Exception e) {
throw new RuntimeException("Failed for waiting stack to valid status: " + e.getMessage(), e);
}
}
private Stack waitStackForRollbackComplete(AmazonCloudFormation client, String stackId) {
Stack stack = waitStackForNoLongerInProgress(client, stackId);
// If failed to rollback the stack, throw Runtime Exception.
if (stack != null && !stack.getStackStatus().equals(StackStatus.ROLLBACK_COMPLETE.toString())) {
String errorMessage = String.format("Failed to rollback the stack: ", stack.getStackStatusReason());
LambdaPlugin.getDefault().logError(errorMessage, null);
throw new RuntimeException(errorMessage);
}
return stack;
}
private Stack waitStackForDeleteComplete(AmazonCloudFormation client, String stackId) {
Stack stack = waitStackForNoLongerInProgress(client, stackId);
// If failed to rollback the stack, throw Runtime Exception.
if (stack != null && !stack.getStackStatus().equals(StackStatus.DELETE_COMPLETE.toString())) {
String errorMessage = String.format("Failed to delete the stack: ", stack.getStackStatusReason());
LambdaPlugin.getDefault().logError(errorMessage, null);
throw new RuntimeException(errorMessage);
}
return stack;
}
private void waitChangeSetCreateComplete(AmazonCloudFormation client, String stackName, String changeSetName) {
try {
DescribeChangeSetResult result;
do {
Thread.sleep(1000L);
result = client.describeChangeSet(new DescribeChangeSetRequest()
.withChangeSetName(changeSetName)
.withStackName(stackName));
} while (result.getStatus().equals(ChangeSetStatus.CREATE_IN_PROGRESS.toString())
|| result.getStatus().equals(ChangeSetStatus.CREATE_PENDING.toString()));
if (result.getStatus().equals(ChangeSetStatus.FAILED.toString())) {
String errorMessage = "Failed to create CloudFormation change set: " + result.getStatusReason();
LambdaPlugin.getDefault().logError(errorMessage, null);
throw new RuntimeException(errorMessage, null);
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
protected void initDataModel() {
ServerlessProjectMetadata metadata = null;
try {
metadata = ProjectMetadataManager.loadServerlessProjectMetadata(dataModel.getProject());
} catch (IOException e) {
LambdaPlugin.getDefault().logError(e.getMessage(), e);
}
dataModel.setMetadata(metadata);
if (metadata != null) {
dataModel.getRegionDataModel().setRegion(RegionUtils.getRegion(metadata.getLastDeploymentRegionId()));
}
if (metadata == null || metadata.getLastDeploymentRegionId() == null) {
dataModel.getRegionDataModel().setRegion(
RegionUtils.isServiceSupportedInCurrentRegion(ServiceAbbreviations.CLOUD_FORMATION)
? RegionUtils.getCurrentRegion()
: RegionUtils.getRegion(LambdaPlugin.DEFAULT_REGION));
}
if (StringUtils.isNullOrEmpty(dataModel.getMetadata().getPackagePrefix())) {
dataModel.getMetadata().setPackagePrefix(getPackagePrefix(dataModel.getHandlerClasses()));
}
}
//A hacky way to get the package prefix when it is not cached in the metadata.
private static String getPackagePrefix(Set<String> handlerClasses) {
if (handlerClasses.isEmpty()) {
return null;
}
String sampleClass = handlerClasses.iterator().next();
int index = sampleClass.lastIndexOf(".function.");
return index == -1 ? null : sampleClass.substring(0, index);
}
@Override
protected void beforeExecution() {
saveMetadata();
List<Parameter> params = dataModel.getParametersDataModel().getParameters();
for ( TemplateParameter parameter : dataModel.getParametersDataModel().getTemplateParameters() ) {
String value = (String) dataModel.getParametersDataModel().getParameterValues().get(parameter.getParameterKey());
params.add(new Parameter().withParameterKey(parameter.getParameterKey()).withParameterValue(value == null ? "" : value));
}
}
private void saveMetadata() {
ServerlessProjectMetadata metadata = dataModel.getMetadata();
metadata.setLastDeploymentRegionId(dataModel.getRegionDataModel().getRegion().getId());
metadata.setLastDeploymentBucket(dataModel.getBucketDataModel().getBucketName());
metadata.setLastDeploymentStack(dataModel.getStackDataModel().getStackName());
try {
ProjectMetadataManager.saveServerlessProjectMetadata(dataModel.getProject(), metadata);
} catch (IOException e) {
LambdaPlugin.getDefault().logError(e.getMessage(), e);
}
}
}
| 7,880 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/wizard/editoraction/DeployServerlessAction.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.lambda.serverless.wizard.editoraction;
import org.eclipse.jface.action.IAction;
import com.amazonaws.eclipse.lambda.LambdaAnalytics;
import com.amazonaws.eclipse.lambda.serverless.handler.DeployServerlessProjectHandler;
import com.amazonaws.eclipse.lambda.upload.wizard.editoraction.AbstractLambdaEditorAction;
public class DeployServerlessAction extends AbstractLambdaEditorAction{
@Override
public void run(IAction action) {
LambdaAnalytics.trackUploadWizardOpenedFromEditorContextMenu();
DeployServerlessProjectHandler.doDeployServerlessTemplate(selectedJavaElement.getJavaProject().getProject());
}
}
| 7,881 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/wizard/editoraction/SamLocalAction.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.lambda.serverless.wizard.editoraction;
import org.eclipse.jface.action.IAction;
import com.amazonaws.eclipse.lambda.launching.SamLocalExecution;
import com.amazonaws.eclipse.lambda.launching.SamLocalExecution.LaunchMode;
import com.amazonaws.eclipse.lambda.upload.wizard.editoraction.AbstractLambdaEditorAction;
/**
* Action of local debugging SAM application triggered by right clicking Lambda function editor
*/
public class SamLocalAction {
public static class RunSamLocalAction extends AbstractLambdaEditorAction {
@Override
public void run(IAction action) {
SamLocalExecution.launch(selectedJavaElement, LaunchMode.RUN);
}
}
public static class DebugSamLocalAction extends AbstractLambdaEditorAction {
@Override
public void run(IAction action) {
SamLocalExecution.launch(selectedJavaElement, LaunchMode.DEBUG);
}
}
} | 7,882 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/template/ServerlessDataModelTemplateData.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.lambda.serverless.template;
/**
* Freemarker template data for serverless-input.ftl and serverless-outout.ftl
* TODO: Serverless models should be added to Lambda event library.
*/
public class ServerlessDataModelTemplateData {
private String packageName;
private String serverlessInputClassName;
private String serverlessOutputClassName;
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getServerlessInputClassName() {
return serverlessInputClassName;
}
public void setServerlessInputClassName(String serverlessInputClassName) {
this.serverlessInputClassName = serverlessInputClassName;
}
public String getServerlessOutputClassName() {
return serverlessOutputClassName;
}
public void setServerlessOutputClassName(String serverlessOutputClassName) {
this.serverlessOutputClassName = serverlessOutputClassName;
}
}
| 7,883 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/template/ServerlessHandlerTemplateData.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.lambda.serverless.template;
/**
* Freemarker template data for serverless-handler.ftl
*/
public class ServerlessHandlerTemplateData {
private String packageName;
private String inputFqcn;
private String outputFqcn;
private String className;
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getInputFqcn() {
return inputFqcn;
}
public void setInputFqcn(String inputFqcn) {
this.inputFqcn = inputFqcn;
}
public String getOutputFqcn() {
return outputFqcn;
}
public void setOutputFqcn(String outputFqcn) {
this.outputFqcn = outputFqcn;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
| 7,884 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/TypeProperties.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.lambda.serverless.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TypeProperties extends AdditionalProperties {
@JsonProperty("Type")
private String type;
@JsonProperty("Properties")
private final Map<String, Object> properties = new HashMap<>();
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
/**
* @return non-null
*/
public Map<String, Object> getProperties() {
return properties;
}
public void addProperty(String key, Object value) {
this.properties.put(key, value);
}
}
| 7,885 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/Resource.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.lambda.serverless.model;
public abstract class Resource extends AdditionalProperties implements TypePropertyable {
}
| 7,886 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/ResourceType.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.lambda.serverless.model;
public enum ResourceType {
AWS_SERVERLESS_FUNCTION("AWS::Serverless::Function"),
AWS_SERVERLESS_API("AWS::Serverless::Api"),
AWS_S3_BUCKET("AWS::S3::Bucket"),
AWS_DYNAMODB_TABLE("AWS::DynamoDB::Table"),
AWS_SERVERLESS_SIMPLE_TABLE("AWS::Serverless::SimpleTable");
private String value;
private ResourceType(String value) {
this.value = value;
}
public String getType() {
return this.value;
}
@Override
public String toString() {
return getType();
}
}
| 7,887 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/TypePropertyable.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.lambda.serverless.model;
public interface TypePropertyable {
TypeProperties toTypeProperties();
}
| 7,888 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/AdditionalProperties.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.lambda.serverless.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
public class AdditionalProperties {
private final Map<String, Object> additionalProperties = new HashMap<>();
/**
* @return non-null
*/
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void addAdditionalProperty(String key, Object value) {
this.additionalProperties.put(key, value);
}
}
| 7,889 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/ServerlessTemplate.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.lambda.serverless.model;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ServerlessTemplate extends AdditionalProperties {
@JsonProperty("AWSTemplateFormatVersion")
private String AWSTemplateFormatVersion;
@JsonProperty("Transform")
private List<String> transform;
@JsonProperty("Description")
private String description;
@JsonProperty("Resources")
private final Map<String, TypeProperties> resources = new HashMap<>();
@JsonProperty("AWSTemplateFormatVersion")
public String getAWSTemplateFormatVersion() {
return AWSTemplateFormatVersion;
}
@JsonProperty("AWSTemplateFormatVersion")
public void setAWSTemplateFormatVersion(String aWSTemplateFormatVersion) {
AWSTemplateFormatVersion = aWSTemplateFormatVersion;
}
public List<String> getTransform() {
return transform;
}
public void setTransform(List<String> transform) {
this.transform = transform;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* @return non-null
*/
public Map<String, TypeProperties> getResources() {
return resources;
}
public void addResource(String key, TypeProperties resource) {
this.resources.put(key, resource);
}
}
| 7,890 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/transform/ServerlessModel.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.lambda.serverless.model.transform;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.eclipse.lambda.serverless.model.AdditionalProperties;
import com.amazonaws.eclipse.lambda.serverless.model.TypeProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ServerlessModel extends AdditionalProperties {
private static final String DEFAULT_AWS_TEMPLATE_FORMAT_VERSION = "2010-09-09";
private static final List<String> DEFAULT_TRANSFORM = Arrays.asList("AWS::Serverless-2016-10-31");
@JsonProperty("AWSTemplateFormatVersion")
private String awsTemplateFormatVersion;
private List<String> transform;
private String description;
private final Map<String, ServerlessFunction> serverlessFunctions = new HashMap<>();
// A map of Lambda handler name to Lambda function physical ID
private final Map<String, String> serverlessFunctionPhysicalIds = new HashMap<>();
// Unrecognized resources
private final Map<String, TypeProperties> additionalResources = new HashMap<>();
/**
* @return non-null
*/
public Map<String, ServerlessFunction> getServerlessFunctions() {
return serverlessFunctions;
}
@JsonProperty("AWSTemplateFormatVersion")
public String getAWSTemplateFormatVersion() {
if (awsTemplateFormatVersion == null) {
awsTemplateFormatVersion = DEFAULT_AWS_TEMPLATE_FORMAT_VERSION;
}
return awsTemplateFormatVersion;
}
public Map<String, String> getServerlessFunctionPhysicalIds() {
return serverlessFunctionPhysicalIds;
}
@JsonProperty("AWSTemplateFormatVersion")
public void setAWSTemplateFormatVersion(String awsTemplateFormatVersion) {
this.awsTemplateFormatVersion = awsTemplateFormatVersion;
}
public List<String> getTransform() {
if (transform == null) {
transform = DEFAULT_TRANSFORM;
}
return transform;
}
public void setTransform(List<String> transform) {
this.transform = transform;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void addServerlessFunction(String key, ServerlessFunction serverlessFunction) {
this.serverlessFunctions.put(key, serverlessFunction);
this.serverlessFunctionPhysicalIds.put(serverlessFunction.getHandler(), key);
}
/**
* @return non-null
*/
public Map<String, TypeProperties> getAdditionalResources() {
return additionalResources;
}
public void addAdditionalResource(String key, TypeProperties additionalResource) {
this.additionalResources.put(key, additionalResource);
}
}
| 7,891 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/transform/DynamoDBTable.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.lambda.serverless.model.transform;
import java.util.List;
public class DynamoDBTable {
private String tableName;
private List<AttributeDefinition> attributeDefinitions;
private List<KeySchema> keySchemas;
private ProvisionedThroughput provisionedThroughput;
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public List<AttributeDefinition> getAttributeDefinitions() {
return attributeDefinitions;
}
public void setAttributeDefinitions(List<AttributeDefinition> attributeDefinitions) {
this.attributeDefinitions = attributeDefinitions;
}
public List<KeySchema> getKeySchemas() {
return keySchemas;
}
public void setKeySchemas(List<KeySchema> keySchemas) {
this.keySchemas = keySchemas;
}
public ProvisionedThroughput getProvisionedThroughput() {
return provisionedThroughput;
}
public void setProvisionedThroughput(ProvisionedThroughput provisionedThroughput) {
this.provisionedThroughput = provisionedThroughput;
}
}
| 7,892 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/transform/Response.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.lambda.serverless.model.transform;
import java.util.Map;
public class Response {
private String statusCode;
private Map<String, String> responseTemplates;
private Map<String, String> responseParameters;
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public Map<String, String> getResponseTemplates() {
return responseTemplates;
}
public void setResponseTemplates(Map<String, String> responseTemplates) {
this.responseTemplates = responseTemplates;
}
public Map<String, String> getResponseParameters() {
return responseParameters;
}
public void setResponseParameters(Map<String, String> responseParameters) {
this.responseParameters = responseParameters;
}
}
| 7,893 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/transform/PrimaryKey.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.lambda.serverless.model.transform;
public class PrimaryKey {
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 7,894 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/transform/CustomIntegration.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.lambda.serverless.model.transform;
import java.util.List;
import java.util.Map;
public class CustomIntegration {
private Map<String, String> requestTemplates;
private String cacheNamespace;
private List<String> cacheKeyParameters;
private Map<String, Response> responses;
public Map<String, String> getRequestTemplates() {
return requestTemplates;
}
public void setRequestTemplates(Map<String, String> requestTemplates) {
this.requestTemplates = requestTemplates;
}
public String getCacheNamespace() {
return cacheNamespace;
}
public void setCacheNamespace(String cacheNamespace) {
this.cacheNamespace = cacheNamespace;
}
public List<String> getCacheKeyParameters() {
return cacheKeyParameters;
}
public void setCacheKeyParameters(List<String> cacheKeyParameters) {
this.cacheKeyParameters = cacheKeyParameters;
}
public Map<String, Response> getResponses() {
return responses;
}
public void setResponses(Map<String, Response> responses) {
this.responses = responses;
}
}
| 7,895 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/transform/ServerlessApi.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.lambda.serverless.model.transform;
import java.util.Map;
import com.amazonaws.eclipse.lambda.serverless.model.Resource;
import com.amazonaws.eclipse.lambda.serverless.model.TypeProperties;
public class ServerlessApi extends Resource {
private String stageName;
private String definitionUri;
private Boolean cacheClusterEnabled;
private Integer cacheClusterSize;
private Map<String, String> variables;
public String getStageName() {
return stageName;
}
public void setStageName(String stageName) {
this.stageName = stageName;
}
public String getDefinitionUri() {
return definitionUri;
}
public void setDefinitionUri(String definitionUri) {
this.definitionUri = definitionUri;
}
public Boolean getCacheClusterEnabled() {
return cacheClusterEnabled;
}
public void setCacheClusterEnabled(Boolean cacheClusterEnabled) {
this.cacheClusterEnabled = cacheClusterEnabled;
}
public Integer getCacheClusterSize() {
return cacheClusterSize;
}
public void setCacheClusterSize(Integer cacheClusterSize) {
this.cacheClusterSize = cacheClusterSize;
}
public Map<String, String> getVariables() {
return variables;
}
public void setVariables(Map<String, String> variables) {
this.variables = variables;
}
@Override
public TypeProperties toTypeProperties() {
// TODO Auto-generated method stub
return null;
}
}
| 7,896 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/transform/ProvisionedThroughput.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.lambda.serverless.model.transform;
public class ProvisionedThroughput {
private Integer readCapacityUnits;
private Integer writeCapacityUnits;
public Integer getReadCapacityUnits() {
return readCapacityUnits;
}
public void setReadCapacityUnits(Integer readCapacityUnits) {
this.readCapacityUnits = readCapacityUnits;
}
public Integer getWriteCapacityUnits() {
return writeCapacityUnits;
}
public void setWriteCapacityUnits(Integer writeCapacityUnits) {
this.writeCapacityUnits = writeCapacityUnits;
}
}
| 7,897 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/transform/KeySchema.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.lambda.serverless.model.transform;
public class KeySchema {
private String attributeName;
private String keyType;
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getKeyType() {
return keyType;
}
public void setKeyType(String keyType) {
this.keyType = keyType;
}
}
| 7,898 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/serverless/model/transform/ServerlessFunction.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.lambda.serverless.model.transform;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.eclipse.lambda.serverless.model.Resource;
import com.amazonaws.eclipse.lambda.serverless.model.ResourceType;
import com.amazonaws.eclipse.lambda.serverless.model.TypeProperties;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ServerlessFunction extends Resource {
private static final String DEFAULT_RUNTIME = "java8";
private static final Integer DEFAULT_TIMEOUT = 300;
private static final Integer DEFAULT_MEMORY_SIZE = 512;
@JsonProperty("Handler")
private String handler;
@JsonProperty("Runtime")
private String runtime;
@JsonProperty("CodeUri")
private String codeUri;
@JsonProperty("Description")
private String description;
@JsonProperty("MemorySize")
private Integer memorySize;
@JsonProperty("Timeout")
private Integer timeout;
@JsonProperty("Role")
private JsonNode role;
@JsonProperty("Policies")
private final List<String> policies = new ArrayList<>();
@JsonIgnore
// These are additional properties in the Type, Properties level.
private final Map<String, Object> additionalTopLevelProperties = new HashMap<>();
public String getHandler() {
return handler;
}
public void setHandler(String handler) {
this.handler = handler;
}
public String getRuntime() {
return runtime == null ? DEFAULT_RUNTIME : runtime;
}
public void setRuntime(String runtime) {
this.runtime = runtime;
}
public String getCodeUri() {
return codeUri;
}
public void setCodeUri(String codeUri) {
this.codeUri = codeUri;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getMemorySize() {
return memorySize == null ? DEFAULT_MEMORY_SIZE : memorySize;
}
public void setMemorySize(Integer memorySize) {
this.memorySize = memorySize;
}
public Integer getTimeout() {
return timeout == null ? DEFAULT_TIMEOUT : timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public JsonNode getRole() {
return role;
}
public void setRole(JsonNode role) {
this.role = role;
}
/**
* @return non-null
*/
public List<String> getPolicies() {
return policies;
}
public void addPolicy(String policy) {
this.policies.add(policy);
}
/**
* @return non-null
*/
public Map<String, Object> getAdditionalTopLevelProperties() {
return additionalTopLevelProperties;
}
public void addAdditionalTopLevelProperty(String key, Object value) {
this.additionalTopLevelProperties.put(key, value);
}
@Override
public TypeProperties toTypeProperties() {
TypeProperties tp = new TypeProperties();
tp.setType(ResourceType.AWS_SERVERLESS_FUNCTION.toString());
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> properties = mapper.convertValue(this, Map.class);
for (Entry<String, Object> entry : properties.entrySet()) {
tp.addProperty(entry.getKey(), entry.getValue());
}
Map<String, Object> topLevelProperties = getAdditionalTopLevelProperties();
for (Entry<String, Object> entry : topLevelProperties.entrySet()) {
tp.addAdditionalProperty(entry.getKey(), entry.getValue());
}
return tp;
}
@Override
public String toString() {
return "ServerlessFunction [handler=" + handler + ", runtime=" + runtime + ", codeUri=" + codeUri
+ ", description=" + description + ", memorySize=" + memorySize + ", timeout=" + timeout + ", role="
+ role + ", policies=" + policies + ", getAdditionalProperties()=" + getAdditionalProperties() + "]";
}
}
| 7,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.