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.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/S3EventSource.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 S3EventSource {
private String bucket;
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
}
| 7,900 |
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/ServerlessSimpleTable.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 com.amazonaws.eclipse.lambda.serverless.model.Resource;
import com.amazonaws.eclipse.lambda.serverless.model.TypeProperties;
public class ServerlessSimpleTable extends Resource {
private PrimaryKey primaryKey;
private ProvisionedThroughput provisionedThroughput;
public PrimaryKey getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(PrimaryKey primaryKey) {
this.primaryKey = primaryKey;
}
public ProvisionedThroughput getProvisionedThroughput() {
return provisionedThroughput;
}
public void setProvisionedThroughput(ProvisionedThroughput provisionedThroughput) {
this.provisionedThroughput = provisionedThroughput;
}
@Override
public TypeProperties toTypeProperties() {
// TODO Auto-generated method stub
return null;
}
}
| 7,901 |
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/AttributeDefinition.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 AttributeDefinition {
private String attributeName;
private String attributeType;
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getAttributeType() {
return attributeType;
}
public void setAttributeType(String attributeType) {
this.attributeType = attributeType;
}
}
| 7,902 |
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/S3Bucket.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 S3Bucket {
private String bucketName;
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
}
| 7,903 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/invoke | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/invoke/handler/InvokeFunctionHandler.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.invoke.handler;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.UUID;
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.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.jdt.core.IJavaElement;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.exceptions.AwsActionException;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.core.util.PluginUtils;
import com.amazonaws.eclipse.lambda.LambdaAnalytics;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.invoke.logs.CloudWatchLogsUtils;
import com.amazonaws.eclipse.lambda.invoke.ui.InvokeFunctionInputDialog;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata.LambdaFunctionDeploymentMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata.LambdaFunctionInvokeMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata.LambdaFunctionMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.ProjectMetadataManager;
import com.amazonaws.eclipse.lambda.ui.LambdaJavaProjectUtil;
import com.amazonaws.eclipse.lambda.upload.wizard.handler.UploadFunctionToLambdaCommandHandler;
import com.amazonaws.eclipse.lambda.upload.wizard.util.FunctionJarExportHelper;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.model.InvocationType;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.InvokeResult;
import com.amazonaws.services.lambda.model.LogType;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeRequest;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeResult;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.util.StringUtils;
public class InvokeFunctionHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IJavaElement selectedJavaElement = LambdaJavaProjectUtil.getSelectedJavaElementFromCommandEvent(event);
if (selectedJavaElement != null) {
try {
invokeLambdaFunctionProject(selectedJavaElement);
} catch (Exception e) {
LambdaPlugin.getDefault().reportException(
"Failed to launch upload function wizard.",
new AwsActionException(AwsToolkitMetricType.LAMBDA_INVOKE_FUNCTION_DIALOG.getName(), e.getMessage(), e));
}
}
return null;
}
public static void invokeLambdaFunctionProject(IJavaElement selectedJavaElement) {
LambdaFunctionProjectMetadata md = null;
IProject project = selectedJavaElement.getJavaProject().getProject();
try {
md = ProjectMetadataManager.loadLambdaProjectMetadata(project);
} catch (IOException e) {
// Log this error but still proceed.
LambdaPlugin.getDefault().logError("Failed to read metadata in the project: " + e.getMessage(), e);
}
if (md != null) {
// Invoke related properties are to be populated within inputDialog
InvokeFunctionInputDialog inputDialog = new InvokeFunctionInputDialog(
Display.getCurrent().getActiveShell(), selectedJavaElement, md);
int retCode = inputDialog.open();
if (retCode == InvokeFunctionInputDialog.INVOKE_BUTTON_ID) {
boolean isProjectDirty = LambdaPlugin.getDefault()
.getProjectChangeTracker().isProjectDirty(project);
if (!md.isLastInvokedHandlerDeployed()) {
askForDeploymentFirst(selectedJavaElement);
return;
}
if (isProjectDirty) {
invokeAfterRepeatingLastDeployment(project, md);
} else {
invokeWithoutDeployment(project, md);
}
} else {
LambdaAnalytics.trackInvokeCanceled();
}
} else {
askForDeploymentFirst(selectedJavaElement);
}
}
private static void invokeAfterRepeatingLastDeployment(final IProject project, final LambdaFunctionProjectMetadata metadata) {
_doInvoke(project, metadata, true);
}
private static void invokeWithoutDeployment(final IProject project, final LambdaFunctionProjectMetadata metadata) {
_doInvoke(project, metadata, false);
}
private static void _doInvoke(final IProject project,
final LambdaFunctionProjectMetadata metadata,
final boolean updateFunctionCode) {
String handlerToBeInvoked = metadata.getLastInvokeHandler();
MessageConsole lambdaConsole = PluginUtils.getOrCreateMessageConsole(
handlerToBeInvoked + " Lambda Console");
lambdaConsole.clearConsole();
ConsolePlugin.getDefault().getConsoleManager().showConsoleView(lambdaConsole);
final MessageConsoleStream lambdaOutput = lambdaConsole.newMessageStream();
final MessageConsoleStream lambdaError = lambdaConsole.newMessageStream();
lambdaError.setColor(new Color(Display.getDefault(), 255, 0, 0));
new Job("Running " + handlerToBeInvoked + " on Lambda...") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
invokeLatestLambdaFunction(project, metadata, updateFunctionCode, lambdaOutput, lambdaError);
} catch (Exception e) {
showLambdaInvocationError(lambdaError, e);
}
LambdaAnalytics.trackInvokeSucceeded();
safelyCloseMessageConsoleStreams(lambdaOutput, lambdaError);
return Status.OK_STATUS;
}
}.schedule();
}
private static void invokeLatestLambdaFunction(IProject project,
LambdaFunctionProjectMetadata metadata,
boolean updateFunctionCode,
MessageConsoleStream lambdaOutput,
MessageConsoleStream lambdaError) throws IOException {
String handlerToBeInvoked = metadata.getLastInvokeHandler();
LambdaFunctionMetadata functionMetadata = metadata.getHandlerMetadata().get(handlerToBeInvoked);
assert (functionMetadata != null && functionMetadata.getDeployment() != null && functionMetadata.getInvoke() != null);
LambdaFunctionDeploymentMetadata deploymentMetadata = functionMetadata.getDeployment();
LambdaFunctionInvokeMetadata invokeMetadata = functionMetadata.getInvoke();
AWSLambda lambda = AwsToolkitCore.getClientFactory().getLambdaClientByRegion(
deploymentMetadata.getRegionId());
String funcName = deploymentMetadata.getAwsLambdaFunctionName();
String bucketName = deploymentMetadata.getAwsS3BucketName();
String invokeInput = invokeMetadata.getInvokeInput();
boolean showLiveLog = invokeMetadata.isShowLiveLog();
if (updateFunctionCode) {
updateFunctionCode(lambda, project, funcName, bucketName, lambdaOutput);
/*
* clear the dirty flag so that the next invoke will not
* attempt to re-upload the code if no change is made to
* the project.
*/
LambdaPlugin.getDefault().getProjectChangeTracker()
.markProjectAsNotDirty(project);
} else {
lambdaOutput
.println("Skip uploading function code since no local change is found...");
}
InvokeResult result = invokeFunction(lambda, invokeInput, funcName, lambdaOutput);
if (showLiveLog) showLambdaLiveLog(result, lambdaOutput, lambdaError);
ProjectMetadataManager.saveLambdaProjectMetadata(project, metadata);
}
private static void safelyCloseMessageConsoleStreams(MessageConsoleStream... streams) {
if (streams == null) return;
try {
for (MessageConsoleStream stream : streams) {
stream.close();
}
} catch (IOException e) {
LambdaPlugin.getDefault().logWarning(
"Failed to close console message stream.", e);
}
}
private static void showLambdaInvocationError(MessageConsoleStream lambdaError, Exception e) {
LambdaAnalytics.trackInvokeFailed();
lambdaError.println("==================== INVOCATION ERROR ====================");
lambdaError.println(e.toString());
}
private static void showLambdaLiveLog(InvokeResult result, MessageConsoleStream lambdaOutput, MessageConsoleStream lambdaError) {
lambdaOutput.println();
lambdaOutput.println("==================== FUNCTION LOG OUTPUT ====================");
String log = CloudWatchLogsUtils.fetchLogsForLambdaFunction(result);
if (log != null) {
lambdaOutput.print(log);
if (log.length() >= CloudWatchLogsUtils.MAX_LAMBDA_LOG_RESULT_LENGTH) {
lambdaError.println("WARNING: Log is truncated for being longer than 4Kb.");
lambdaError.println("To see the complete log, go to AWS CloudWatch Logs console.");
}
}
}
private static void updateFunctionCode(AWSLambda lambda, IProject project,
String funcName, String bucketName, MessageConsoleStream out)
throws IOException {
out.println("Uploading function code to " + funcName + "...");
File funcCodeFile = FunctionJarExportHelper.exportProjectToJarFile(
project, false);
String randomKeyName = UUID.randomUUID().toString();
AmazonS3 s3 = AwsToolkitCore.getClientFactory()
.getS3ClientForBucket(bucketName);
s3.putObject(bucketName, randomKeyName, funcCodeFile);
UpdateFunctionCodeResult result = lambda.updateFunctionCode(
new UpdateFunctionCodeRequest()
.withFunctionName(funcName)
.withS3Bucket(bucketName)
.withS3Key(randomKeyName));
// Clean up ourself after the function is created
try {
s3.deleteObject(bucketName, randomKeyName);
} catch (Exception e) {
out.println(String.format(
"Failed to cleanup function code in S3. " +
"Please remove the object manually s3://%s/%s",
bucketName, randomKeyName));
}
out.println("Upload success. Function ARN: " + result.getFunctionArn());
}
private static InvokeResult invokeFunction(AWSLambda lambda, String input,
String funcName, MessageConsoleStream out) {
out.println("Invoking function...");
InvokeRequest invokeRequest = new InvokeRequest()
.withFunctionName(funcName)
.withInvocationType(InvocationType.RequestResponse)
.withLogType(LogType.Tail)
.withPayload(input);
InvokeResult result = lambda.invoke(invokeRequest);
out.println("==================== FUNCTION OUTPUT ====================");
out.print(readPayload(result.getPayload()));
return result;
}
private static void askForDeploymentFirst(IJavaElement selectedJavaElement) {
MessageDialog dialog = new MessageDialog(
Display.getCurrent().getActiveShell(),
"Function not uploaded yet", null,
"You need to upload the function to Lambda before invoking it.",
MessageDialog.INFORMATION,
new String[] { "Upload now", "Cancel"}, 0);
int result = dialog.open();
if (result == 0) {
LambdaAnalytics.trackUploadWizardOpenedBeforeFunctionInvoke();
UploadFunctionToLambdaCommandHandler.doUploadFunctionProjectToLambda(selectedJavaElement);
}
}
private static String readPayload(ByteBuffer payload) {
return new String(payload.array(), StringUtils.UTF8);
}
}
| 7,904 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/invoke | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/invoke/ui/InvokeFunctionInputDialog.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.invoke.ui;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCombo;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newFillingLabel;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newRadioButton;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata;
import com.amazonaws.eclipse.lambda.ui.LambdaJavaProjectUtil;
import com.amazonaws.eclipse.lambda.upload.wizard.util.UploadFunctionUtil;
public class InvokeFunctionInputDialog extends Dialog {
public static final int INVOKE_BUTTON_ID = IDialogConstants.OK_ID;
private static final int PREFERRED_WIDTH = 600;
private static final int PREFERRED_HEIGHT = 400;
private final IProject project;
private final IJavaElement selectedJavaElement;
private final LambdaFunctionProjectMetadata md;
private Combo lambdaHandlerCombo;
private Button jsonInputFileButton;
private Combo jsonInputFileCombo;
private String suggestedInputBoxContent;
private Button jsonInputButton;
private Text inputBox;
private Button showLiveLogButton;
private static final String LOADING = "Loading...";
private static final String NONE_FOUND = "None found";
public InvokeFunctionInputDialog(Shell parentShell, IJavaElement selectedJavaElement, LambdaFunctionProjectMetadata md) {
super(parentShell);
this.project = selectedJavaElement.getJavaProject().getProject();
this.selectedJavaElement = selectedJavaElement;
this.md = md;
}
public boolean isInputBoxContentModified() {
return !inputBox.equals(suggestedInputBoxContent);
}
@Override
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
initUI(container);
initDefaultValue();
return container;
}
@Override
protected boolean isResizable() {
return true;
}
private void initUI(Composite container) {
container.setLayout(new GridLayout(2, true));
newFillingLabel(container, "Select one of the Lambda Handlers to invoke:", 1);
lambdaHandlerCombo = newCombo(container, 1);
lambdaHandlerCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onLambdaHandlerComboSelected();
}
});
jsonInputFileButton = newRadioButton(container, "Select one of the JSON files as input: ", 1, false, new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onRadioButtonSelected();
}
});
jsonInputFileCombo = newCombo(container, 1);
jsonInputFileCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onJsonFileSelectionChange();
}
});
jsonInputButton = newRadioButton(container, "Enter the JSON input for your function", 2, false, new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onRadioButtonSelected();
}
});
inputBox = new Text(container, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
gridData.horizontalSpan = 2;
inputBox.setLayoutData(gridData);
inputBox.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
md.setLastInvokeInput(inputBox.getText());
}
});
showLiveLogButton = new Button(container, SWT.CHECK);
showLiveLogButton.setText("Show live log");
showLiveLogButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
md.setLastInvokeShowLiveLog(showLiveLogButton.getSelection());
}
});
}
private void initDefaultValue() {
loadLambdaHandlerAsync();
loadJsonFilesAsync();
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, INVOKE_BUTTON_ID, "Invoke", true);
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false);
}
@Override
protected Point getInitialSize() {
return new Point(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
private void loadLambdaHandlerAsync() {
Display.getDefault().syncExec(() -> {
lambdaHandlerCombo.setItems(new String[] {LOADING});
lambdaHandlerCombo.select(0);
lambdaHandlerCombo.setEnabled(false);
});
Display.getDefault().asyncExec(() -> {
Set<String> handlerClasses = UploadFunctionUtil.findValidHandlerClass(project);
if (handlerClasses == null || handlerClasses.isEmpty()) {
lambdaHandlerCombo.setItems(new String[] {NONE_FOUND});
lambdaHandlerCombo.select(0);
disableAllTheWidegets();
} else {
lambdaHandlerCombo.removeAll();
for (String handlerClass : handlerClasses) {
lambdaHandlerCombo.add(handlerClass);
}
// The current selected element has the highest priority for this invoke.
String defaultHandler = LambdaJavaProjectUtil.figureOutDefaultLambdaHandler(selectedJavaElement, handlerClasses);
// If the current selected element is not a valid handler, then we choose the last deployed handler.
if (defaultHandler == null || !handlerClasses.contains(defaultHandler)) {
defaultHandler = md.getLastDeploymentHandler();
}
// If the last deployed handler is not valid, we choose the last invoked handler.
if (defaultHandler == null) {
defaultHandler = md.getLastInvokeHandler();
}
// If the last deployed handler is not valid, we choose a random handler from the valid handler set.
if (defaultHandler == null || !handlerClasses.contains(defaultHandler)) {
defaultHandler = handlerClasses.iterator().next();
}
lambdaHandlerCombo.select(lambdaHandlerCombo.indexOf(defaultHandler));
onLambdaHandlerComboSelected();
lambdaHandlerCombo.setEnabled(true);
}
});
}
private void disableAllTheWidegets() {
lambdaHandlerCombo.setEnabled(false);
jsonInputFileButton.setEnabled(false);
jsonInputButton.setEnabled(false);
jsonInputFileCombo.setEnabled(false);
inputBox.setEnabled(false);
showLiveLogButton.setEnabled(false);
}
private void loadJsonFilesAsync() {
Display.getDefault().syncExec(() -> {
jsonInputFileCombo.setItems(new String[] {LOADING});
jsonInputFileCombo.select(0);
jsonInputFileCombo.setEnabled(false);
});
Display.getDefault().asyncExec(() -> {
List<IFile> jsonFiles = null;
try {
jsonFiles = findJsonFiles(project);
} catch (CoreException e) {
LambdaPlugin.getDefault().logWarning(
"Failed to search for .json files in the project", e);
}
if (jsonFiles == null || jsonFiles.isEmpty()) {
jsonInputFileCombo.setItems(new String[] {NONE_FOUND});
jsonInputFileCombo.select(0);
jsonInputFileCombo.setEnabled(false);
jsonInputButton.setSelection(true);
jsonInputFileButton.setSelection(false);
onRadioButtonSelected();
} else {
jsonInputFileCombo.removeAll();
for (IFile jsonFile : jsonFiles) {
jsonInputFileCombo.add(jsonFile.getFullPath().toOSString());
jsonInputFileCombo.setData(jsonFile.getFullPath().toOSString(), jsonFile);
}
int index = jsonInputFileCombo.indexOf(md.getLastInvokeJsonFile());
if (index < 0) {
index = 0;
}
jsonInputFileCombo.select(index);
onJsonFileSelectionChange();
}
});
}
private List<IFile> findJsonFiles(IProject project) throws CoreException {
final List<IFile> jsonFiles = new LinkedList<>();
project.accept((res) -> {
if (res instanceof IFile) {
IFile file = (IFile) res;
IPath fullPath = file.getFullPath();
if (file.getName().endsWith(".json")) {
// Skip hidden folder or files
int i = 0;
while (i < fullPath.segmentCount()) {
if (fullPath.segment(i).startsWith(".")) {
break;
}
++i;
}
if (i == fullPath.segmentCount()) {
jsonFiles.add(file);
}
}
}
return true;
});
return jsonFiles;
}
private void onLambdaHandlerComboSelected() {
String handlerClass = lambdaHandlerCombo.getItem(lambdaHandlerCombo.getSelectionIndex());
md.setLastInvokeHandler(handlerClass);
jsonInputFileButton.setSelection(md.getLastInvokeSelectJsonFile());
jsonInputButton.setSelection(!md.getLastInvokeSelectJsonFile());
onRadioButtonSelected();
showLiveLogButton.setSelection(md.getLastInvokeShowLiveLog());
}
private void onRadioButtonSelected() {
jsonInputFileCombo.setEnabled(jsonInputFileButton.getSelection());
inputBox.setEditable(jsonInputButton.getSelection());
md.setLastInvokeSelectJsonFile(jsonInputFileButton.getSelection());
md.setLastInvokeSelectJsonInput(jsonInputButton.getSelection());
if (jsonInputFileButton.getSelection()) {
onJsonFileSelectionChange();
} else if (jsonInputButton.getSelection()) {
inputBox.setText(md.getLastInvokeInput());
}
}
private void onJsonFileSelectionChange() {
if (jsonInputFileButton.getSelection() == false) {
return;
}
IFile file = (IFile) jsonInputFileCombo.getData(jsonInputFileCombo.getText());
if (file == null) {
return;
}
try {
String fileContent = IOUtils.toString(file.getContents());
inputBox.setText(fileContent);
suggestedInputBoxContent = fileContent;
md.setLastInvokeJsonFile(jsonInputFileCombo.getText());
md.setLastInvokeInput(fileContent);
} catch (Exception ignored) {
return;
}
}
}
| 7,905 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/invoke | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/invoke/logs/CloudWatchLogsUtils.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.invoke.logs;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.services.lambda.model.InvokeResult;
import com.amazonaws.services.logs.AWSLogs;
import com.amazonaws.services.logs.model.AWSLogsException;
import com.amazonaws.services.logs.model.DescribeLogStreamsRequest;
import com.amazonaws.services.logs.model.DescribeLogStreamsResult;
import com.amazonaws.services.logs.model.GetLogEventsRequest;
import com.amazonaws.services.logs.model.GetLogEventsResult;
import com.amazonaws.services.logs.model.LogStream;
import com.amazonaws.services.logs.model.OrderBy;
import com.amazonaws.services.logs.model.OutputLogEvent;
import com.amazonaws.util.Base64;
import com.amazonaws.util.CodecUtils;
import com.amazonaws.util.StringUtils;
public class CloudWatchLogsUtils {
public static final int MAX_LAMBDA_LOG_RESULT_LENGTH = 4 * 1024;// 4Kb
public static String fetchLogsForLambdaFunction(InvokeResult invokeResult) {
if (invokeResult != null && !StringUtils.isNullOrEmpty(invokeResult.getLogResult())) {
return CodecUtils.toStringDirect(Base64.decode((invokeResult.getLogResult())));
}
return null;
}
public static List<LogStream> listLogStreams(AWSLogs client, String groupName) {
List<LogStream> streams = new ArrayList<>();
DescribeLogStreamsRequest request = new DescribeLogStreamsRequest()
.withLogGroupName(groupName)
.withOrderBy(OrderBy.LastEventTime)
.withDescending(false);
DescribeLogStreamsResult result = null;
try {
do {
result = client.describeLogStreams(request);
streams.addAll(result.getLogStreams());
request.setNextToken(result.getNextToken());
} while (result.getNextToken() != null);
} catch (AWSLogsException e) {
LambdaPlugin.getDefault().logError(e.getMessage(), e);
} catch (Exception ee) {
LambdaPlugin.getDefault().reportException(ee.getMessage(), ee);
}
return streams;
}
public static List<OutputLogEvent> listLogEvents(AWSLogs client, String groupName, List<LogStream> streamNames) {
List<OutputLogEvent> events = new ArrayList<>();
for (LogStream stream : streamNames) {
GetLogEventsRequest getLogEventsRequest = new GetLogEventsRequest()
.withLogGroupName(groupName)
.withLogStreamName(stream.getLogStreamName());
GetLogEventsResult getLogEventResult = null;
do {
getLogEventResult = client.getLogEvents(getLogEventsRequest);
events.addAll(getLogEventResult.getEvents());
getLogEventsRequest.setNextToken(getLogEventResult.getNextBackwardToken());
} while (!getLogEventResult.getEvents().isEmpty());
}
return events;
}
public static String convertLogEventsToString(List<OutputLogEvent> events) {
StringBuilder builder = new StringBuilder();
for (OutputLogEvent event : events) {
builder.append(String.format("%s\t%s\n",
longTimeToHumanReadible(event.getTimestamp()), event.getMessage()));
}
return builder.toString();
}
public static String longTimeToHumanReadible(long time) {
return new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z").format(new Date (time));
}
}
| 7,906 |
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/launching/SamLocalConstants.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.launching;
/**
* Constants used in SAM Local feature, mostly are attribute constants of SAM Local Launch configurations.
*/
public class SamLocalConstants {
// Preference name for AWS SAM Local executable
public static String P_SAM_LOCAL_EXECUTABLE = "AwsSamLocalExecutable";
// SAM Local process type. This is configured in plugin.xml
public static String PROCESS_TYPE = "sam_local";
// Attribute names for executing a SAM Local command.
public static String A_SAM = "sam";
public static String A_MAVEN_GOALS = "maven-goals";
public static String A_ACTION = "action";
public static String A_PROJECT = "project";
// These attribute names must be identical to those of the command line parameter names
public static String A_PROFILE = "profile";
public static String A_TEMPLATE = "template";
public static String A_ENV_VARS = "env-vars";
public static String A_DEBUG_PORT = "debug-port";
public static String A_REGION = "region";
public static String A_CODE_URI = "code-uri";
public static String A_TIME_OUT = "timeout";
// Attributes for `sam local invoke` only
public static String A_LAMBDA_IDENTIFIER = "lambda-id";
public static String A_EVENT = "event";
// Attributes for `sam local start-api` only
public static String A_PORT = "port";
public static String A_HOST = "host";
// Doc links
public static String LINKS_INSTALL_SAM_LOCAL = "https://github.com/awslabs/aws-sam-local#installation";
public static String LINKS_SAM_LOCAL_ANNOUNCEMENT = "https://aws.amazon.com/about-aws/whats-new/2017/08/introducing-aws-sam-local-a-cli-tool-to-test-aws-lambda-functions-locally/";
}
| 7,907 |
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/launching/SamLocalTab.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.launching;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_ACTION;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_CODE_URI;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_DEBUG_PORT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_ENV_VARS;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_EVENT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_HOST;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_LAMBDA_IDENTIFIER;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_MAVEN_GOALS;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_PORT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_PROFILE;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_PROJECT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_REGION;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_SAM;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_TEMPLATE;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_TIME_OUT;
import java.util.Arrays;
import java.util.Collection;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoProperties;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.core.ui.AccountSelectionComposite;
import com.amazonaws.eclipse.core.ui.ImportFileComposite;
import com.amazonaws.eclipse.core.ui.RegionComposite;
import com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory;
import com.amazonaws.eclipse.core.util.PluginUtils;
import com.amazonaws.eclipse.core.validator.FilePathValidator;
import com.amazonaws.eclipse.core.validator.IntegerRangeValidator;
import com.amazonaws.eclipse.core.validator.WorkspacePathValidator;
import com.amazonaws.eclipse.core.widget.ComboViewerComplex;
import com.amazonaws.eclipse.core.widget.TextComplex;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
import com.amazonaws.eclipse.lambda.LambdaConstants;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.dialog.SamLocalGenerateEventDialog;
import com.amazonaws.eclipse.lambda.dialog.SamLocalGenerateEventDialog.SamLocalLambdaEventDataModel;
import com.amazonaws.eclipse.lambda.preferences.SamLocalPreferencePage;
import com.amazonaws.eclipse.lambda.project.wizard.model.RunSamLocalDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.model.RunSamLocalDataModel.SamAction;
import com.amazonaws.eclipse.lambda.project.wizard.model.RunSamLocalDataModel.SamLocalInvokeFunctionDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.model.RunSamLocalDataModel.SamLocalStartApiDataModel;
import com.amazonaws.eclipse.lambda.serverless.model.transform.ServerlessModel;
import com.amazonaws.eclipse.lambda.serverless.validator.ServerlessTemplateFilePathValidator;
public class SamLocalTab extends AbstractLaunchConfigurationTab {
private final RunSamLocalDataModel dataModel = new RunSamLocalDataModel();
private final SamLocalInvokeFunctionDataModel invokeDataModel = new SamLocalInvokeFunctionDataModel();
private final SamLocalStartApiDataModel startApiDataModel = new SamLocalStartApiDataModel();
private final DataBindingContext bindingContext;
private final AggregateValidationStatus aggregateValidationStatus;
// UI
// AWS specific UI
private AccountSelectionComposite accountComposite;
private RegionComposite regionComposite;
// SAM Local UI for common settings
private ImportFileComposite workspaceComposite;
private TextComplex mavenGoalsComplex;
private TextComplex samLocalExecutableComplex;
private ImportFileComposite templateFileComposite;
private ImportFileComposite envvarFileComposite;
private TextComplex debugPortComplex;
// UI for Lambda function settings
private TextComplex codeUriComplex;
private TextComplex timeoutComplex;
private ComboViewerComplex<SamAction> samCommandsComboViewer;
private Group samCommandGroup;
// SAM Local invoke specific UI
private ComboViewerComplex<String> lambdaPhysicalIdCombo;
private ImportFileComposite eventFileComposite;
// SAM Local start-api specific UI
private TextComplex hostComplex;
private TextComplex portComplex;
private ExpandableComposite advancedSettingsExpandable;
public SamLocalTab() {
this.bindingContext = new DataBindingContext();
this.aggregateValidationStatus = new AggregateValidationStatus(
bindingContext, AggregateValidationStatus.MAX_SEVERITY);
}
@Override
public boolean isValid(ILaunchConfiguration launchConfig) {
setErrorMessage(null);
IStatus status = getValidationStatus();
if (status == null) {
return true;
}
if (status.getSeverity() != IStatus.OK) {
setErrorMessage(status.getMessage());
return false;
}
return true;
}
private void entriesChanges() {
setDirty(true);
updateLaunchConfigurationDialog();
}
private IStatus getValidationStatus() {
if (aggregateValidationStatus == null) return null;
Object value = aggregateValidationStatus.getValue();
if (!(value instanceof IStatus)) return null;
return (IStatus)value;
}
private void createAwsScopeGroup(Composite composite) {
Group group = WizardWidgetFactory.newGroup(composite, "AWS Configuration");
accountComposite = new AccountSelectionComposite(group, SWT.NONE);
accountComposite.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
dataModel.setAccount(AwsToolkitCore.getDefault().getAccountManager()
.getAccountInfo(accountComposite.getSelectedAccountId()));
entriesChanges();
}
});
regionComposite = RegionComposite.builder()
.parent(group)
.bindingContext(bindingContext)
.dataModel(dataModel.getRegionDataModel())
.serviceName(ServiceAbbreviations.LAMBDA)
.addListener(e -> entriesChanges())
.build();
}
private void createAdvancedSettingsGroup(Composite composite) {
Group group = WizardWidgetFactory.newGroup(composite, "SAM Local Configuration");
mavenGoalsComplex = TextComplex.builder(WizardWidgetFactory.newComposite(group, 1, 2, false),
bindingContext, PojoProperties.value(RunSamLocalDataModel.P_MAVEN_GOALS).observe(dataModel))
.defaultValue(dataModel.getMavenGoals())
.labelValue("Maven goals: ")
.addValidator(new NotEmptyValidator("Maven goals must not be empty!"))
.modifyListener(e -> entriesChanges())
.textMessage("Maven goals for generating the uber jar of your Lambda project.")
.build();
Composite samLocalRuntimeComposite = WizardWidgetFactory.newComposite(group, 1, 3);
samLocalExecutableComplex = TextComplex.builder(
samLocalRuntimeComposite, bindingContext, PojoProperties.value(
RunSamLocalDataModel.P_SAM_RUNTIME).observe(dataModel))
.createLabel(true)
.labelValue("SAM runtime: ")
.addValidator(new FilePathValidator("SAM runtime"))
.textMessage("AWS SAM Local executable path.")
.modifyListener(e -> entriesChanges())
.build();
// Only disable this Text widget but not the validation.
samLocalExecutableComplex.getText().setEditable(false);
Link link = new Link(samLocalRuntimeComposite, SWT.NONE);
link.setText("<A>Configure AWS SAM Local...</A>");
link.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
PreferencesUtil.createPreferenceDialogOn(Display.getDefault().getActiveShell(),
SamLocalPreferencePage.ID, new String[] { SamLocalPreferencePage.ID }, null).open();
samLocalExecutableComplex.setText(LambdaPlugin.getDefault().getPreferenceStore().getString(
SamLocalConstants.P_SAM_LOCAL_EXECUTABLE));
}
});
debugPortComplex = TextComplex.builder(WizardWidgetFactory.newComposite(group, 1, 2, false),
bindingContext, PojoProperties.value(RunSamLocalDataModel.P_DEBUG_PORT).observe(dataModel))
.defaultValue(String.valueOf(dataModel.getDebugPort()))
.labelValue("Debug port: ")
.addValidator(new IntegerRangeValidator("Debug port", 1024, 65535))
.modifyListener(e -> entriesChanges())
.textMessage("When specified, Lambda function container will start in debug mode and will expose this port on localhost.")
.build();
envvarFileComposite = ImportFileComposite.builder(group, bindingContext, dataModel.getEnvvarFileLocationDataModel())
.textLabel("Env vars: ")
.filePathValidator(new WorkspacePathValidator("Env vars file", true))
.modifyListener(e -> entriesChanges())
.textMessage("JSON file containing values for Lambda function's environment variables.")
.buildWorkspaceFileBrowser();
}
private void createLambdaFunctionGroup(Composite composite) {
Group group = WizardWidgetFactory.newGroup(composite, "Lambda Function Configuration");
codeUriComplex = TextComplex.builder(WizardWidgetFactory.newComposite(group, 1, 2, false),
bindingContext, PojoProperties.value(RunSamLocalDataModel.P_CODE_URI).observe(dataModel))
.labelValue("Code URI: ")
.modifyListener(e -> entriesChanges())
.textMessage("Location to the function code as a Lambda deployment package.")
.build();
timeoutComplex = TextComplex.builder(WizardWidgetFactory.newComposite(group, 1, 2, false),
bindingContext, PojoProperties.value(RunSamLocalDataModel.P_TIME_OUT).observe(dataModel))
.defaultValue(String.valueOf(RunSamLocalDataModel.DEFAULT_TIME_OUT))
.addValidator(new IntegerRangeValidator("Lambda function timeout", 0, 900))
.labelValue("Timeout (secs): ")
.modifyListener(e -> entriesChanges())
.textMessage("Lambda function execution time (in seconds) after which Lambda terminates the function.")
.build();
}
private void createSamLocalConfigSection(Composite composite) {
Group group = WizardWidgetFactory.newGroup(composite, "SAM Local Configuration");
WizardWidgetFactory.newLink(
group,
LambdaConstants.webLinkListener,
"AWS Toolkit for Eclipse is using <a href=\""
+ SamLocalConstants.LINKS_SAM_LOCAL_ANNOUNCEMENT
+ "\">AWS SAM Local</a> for locally debugging your Lambda function. You need to preinstall <a href=\""
+ SamLocalConstants.LINKS_INSTALL_SAM_LOCAL
+ "\">Docker and SAM</a> for this feature.", 1, 100, 30);
workspaceComposite = ImportFileComposite.builder(group, bindingContext, dataModel.getWorkspaceDataModel())
.textLabel("Project:")
.filePathValidator(new NotEmptyValidator("Project must be specified!"))
.modifyListener(e -> {
entriesChanges();
onProjectSelectChanged();
})
.textMessage("Target SAM project which must be a Maven project.")
.buildWorkspaceProjectBrowser();
templateFileComposite = ImportFileComposite.builder(group, bindingContext, dataModel.getTemplateFileLocationDataModel())
.textLabel("Template:")
.filePathValidator(new ServerlessTemplateFilePathValidator())
.modifyListener(e -> {
entriesChanges();
onSamLocalTemplateFileChanged();
})
.textMessage("AWS SAM template file (default: \"serverless.[template|json], sam.[template|json]\")")
.buildWorkspaceFileBrowser();
samCommandsComboViewer = ComboViewerComplex.<SamAction>builder()
.composite(WizardWidgetFactory.newComposite(group, 1, 2, false))
.bindingContext(bindingContext)
.pojoObservableValue(PojoProperties.value(RunSamLocalDataModel.P_SAM_ACTION).observe(dataModel))
.addListeners((e) -> {
onSamCommandsComboViewerSelect();
entriesChanges();
})
.items(SamAction.toList())
.labelValue("Run as: ")
.labelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
if (element instanceof SamAction) {
SamAction samAction = (SamAction) element;
return samAction.getDescription();
} else {
return super.getText(element);
}
}
})
.build();
}
private void onSamCommandsComboViewerSelect() {
switch (dataModel.getSamAction()) {
case INVOKE:
dataModel.setActionDataModel(invokeDataModel);
createInvokeSection();
break;
case START_API:
dataModel.setActionDataModel(startApiDataModel);
createStartApiSection();
break;
}
}
private void onProjectSelectChanged() {
String projectName = dataModel.getWorkspaceDataModel().getFilePath();
String codeUri = SamLocalPathFinder.findCodeUri(projectName);
codeUriComplex.setText(codeUri);
}
private void onSamLocalTemplateFileChanged() {
if (lambdaPhysicalIdCombo == null) {
return;
}
Collection<String> data = getLambdaFunctionPhysicalIDs();
lambdaPhysicalIdCombo.getComboViewer().setInput(data);
if (!data.isEmpty()) {
lambdaPhysicalIdCombo.selectItem(data.iterator().next());
}
lambdaPhysicalIdCombo.getComboViewer().refresh();
}
private static final String UNAVAILABLE_PHYSICAL_ID = "Lambda function not found...";
private Collection<String> getLambdaFunctionPhysicalIDs() {
ServerlessTemplateFilePathValidator validator = new ServerlessTemplateFilePathValidator();
try {
ServerlessModel model = validator.validateFilePath(dataModel.getTemplateFileLocationDataModel().getFilePath());
return model.getServerlessFunctions().keySet();
} catch (Exception e) {
return Arrays.asList(UNAVAILABLE_PHYSICAL_ID);
}
}
private void createSamLocalActionSection(Composite parent) {
samCommandGroup = WizardWidgetFactory.newGroup(parent, "SAM Local Command Configuration");
onSamCommandsComboViewerSelect();
}
private void createInvokeSection() {
for (Control control : samCommandGroup.getChildren()) {
control.dispose();
}
hostComplex = null;
portComplex = null;
lambdaPhysicalIdCombo = ComboViewerComplex.<String>builder()
.bindingContext(bindingContext)
.composite(WizardWidgetFactory.newComposite(samCommandGroup, 1, 2, false))
.labelValue("Function identifier: ")
.labelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
if (element instanceof String) {
String text = (String) element;
return text;
}
return super.getText(element);
}
})
.pojoObservableValue(PojoProperties.value(invokeDataModel.P_LAMBDA_IDENTIFIER).observe(invokeDataModel))
.build();
onSamLocalTemplateFileChanged();
Composite composite = WizardWidgetFactory.newComposite(samCommandGroup, 1, 2, false);
eventFileComposite = ImportFileComposite.builder(composite, bindingContext, invokeDataModel.getEventFileLocationDataModel())
.textLabel("Event:")
.filePathValidator(new WorkspacePathValidator("Event", false))
.modifyListener(e -> entriesChanges())
.textMessage("JSON file containing event data passed to the Lambda function during invoke")
.buildWorkspaceFileBrowser();
Button generateEventButton = WizardWidgetFactory.newPushButton(composite, "Generate", 1);
generateEventButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
SamLocalGenerateEventDialog generateEventDialog = new SamLocalGenerateEventDialog(getShell());
int returnValue = generateEventDialog.open();
if (returnValue == Window.OK) {
SamLocalLambdaEventDataModel dataModel = generateEventDialog.getDataModel();
IPath resultPath = dataModel.getResultPath();
eventFileComposite.setFilePath(PluginUtils.variablePluginGenerateWorkspacePath(resultPath));
}
}
});
samCommandGroup.layout();
}
private void createStartApiSection() {
for (Control control : samCommandGroup.getChildren()) {
control.dispose();
}
lambdaPhysicalIdCombo = null;
eventFileComposite = null;
Composite composite = WizardWidgetFactory.newComposite(samCommandGroup, 1, 2);
hostComplex = TextComplex.builder(composite, bindingContext, PojoProperties.value(SamLocalStartApiDataModel.P_HOST).observe(startApiDataModel))
.defaultValue(startApiDataModel.getHost())
.labelValue("Host:")
.textMessage("Local hostname or IP address to bind to (default: \"127.0.0.1\")")
.modifyListener(e -> entriesChanges())
.build();
portComplex = TextComplex.builder(composite, bindingContext, PojoProperties.value(SamLocalStartApiDataModel.P_PORT).observe(startApiDataModel))
.defaultValue(String.valueOf(startApiDataModel.getPort()))
.labelValue("Port:")
.textMessage("Local port number to listen on (default: \"3000\")")
.modifyListener(e -> entriesChanges())
.build();
samCommandGroup.layout();
}
@Override
public void createControl(Composite parent) {
Composite rootComposite = WizardWidgetFactory.newComposite(parent, 1, 1);
setControl(rootComposite);
rootComposite.setLayout(new GridLayout(1, false));
createSamLocalConfigSection(rootComposite);
createSamLocalActionSection(rootComposite);
createAdvancedSettingSection(rootComposite);
dataModel.setAccount(AwsToolkitCore.getDefault().getAccountManager()
.getAccountInfo(accountComposite.getSelectedAccountId()));
}
private void createAdvancedSettingSection(final Composite parent) {
advancedSettingsExpandable = new ExpandableComposite(parent, SWT.NONE,
ExpandableComposite.TWISTIE | ExpandableComposite.COMPACT | ExpandableComposite.EXPANDED);
advancedSettingsExpandable.setText("Advanced Settings");
advancedSettingsExpandable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Composite expandableComposite = WizardWidgetFactory.newComposite(advancedSettingsExpandable, 1, 1);
advancedSettingsExpandable.setClient(expandableComposite);
advancedSettingsExpandable.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
Shell shell = parent.getShell();
shell.layout(true, true);
}
});
createAwsScopeGroup(expandableComposite);
createAdvancedSettingsGroup(expandableComposite);
createLambdaFunctionGroup(expandableComposite);
}
@Override
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
}
@Override
public void initializeFrom(ILaunchConfiguration configuration) {
accountComposite.selectAccountName(getAttribute(configuration, A_PROFILE, RunSamLocalDataModel.DEFAULT_PROFILE));
dataModel.setAccount(AwsToolkitCore.getDefault().getAccountManager()
.getAccountInfo(accountComposite.getSelectedAccountId()));
regionComposite.selectAwsRegion(RegionUtils.getRegion(getAttribute(configuration, A_REGION, RunSamLocalDataModel.DEFAULT_REGION)));
String projectName = getAttribute(configuration, A_PROJECT, "");
workspaceComposite.setFilePath(projectName);
mavenGoalsComplex.setText(getAttribute(configuration, A_MAVEN_GOALS, RunSamLocalDataModel.DEFAULT_MAVEN_GOALS));
samLocalExecutableComplex.setText(getAttribute(configuration, A_SAM,
LambdaPlugin.getDefault().getPreferenceStore().getString(SamLocalConstants.P_SAM_LOCAL_EXECUTABLE)));
debugPortComplex.setText(getAttribute(configuration, A_DEBUG_PORT, String.valueOf(RunSamLocalDataModel.DEFAULT_DEBUG_PORT)));
templateFileComposite.setFilePath(getAttribute(configuration, A_TEMPLATE, SamLocalPathFinder.findTemplateFile(projectName)));
envvarFileComposite.setFilePath(getAttribute(configuration, A_ENV_VARS, ""));
codeUriComplex.setText(getAttribute(configuration, A_CODE_URI, SamLocalPathFinder.findCodeUri(projectName)));
timeoutComplex.setText(getAttribute(configuration, A_TIME_OUT, String.valueOf(RunSamLocalDataModel.DEFAULT_TIME_OUT)));
SamAction samCommand = SamAction.fromValue(getAttribute(configuration, A_ACTION, SamAction.INVOKE.getName()));
samCommandsComboViewer.selectItem(samCommand);
switch (samCommand) {
case INVOKE:
lambdaPhysicalIdCombo.selectItem(getAttribute(configuration, A_LAMBDA_IDENTIFIER, (String) null));
eventFileComposite.setFilePath(getAttribute(configuration, A_EVENT, SamLocalPathFinder.findEventFile(projectName)));
break;
case START_API:
hostComplex.setText(getAttribute(configuration, A_HOST, SamLocalStartApiDataModel.DEFAULT_HOST));
portComplex.setText(getAttribute(configuration, A_PORT, String.valueOf(SamLocalStartApiDataModel.DEFAULT_PORT)));
break;
}
advancedSettingsExpandable.setExpanded(false);
setDirty(false);
}
@Override
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
configuration.setAttribute(A_PROFILE, dataModel.getAccount().getAccountName());
configuration.setAttribute(A_REGION, dataModel.getRegionDataModel().getRegionId());
configuration.setAttribute(A_PROJECT, dataModel.getWorkspaceDataModel().getFilePath());
configuration.setAttribute(A_MAVEN_GOALS, dataModel.getMavenGoals());
configuration.setAttribute(A_SAM, dataModel.getSamRuntime());
configuration.setAttribute(A_DEBUG_PORT, String.valueOf(dataModel.getDebugPort()));
configuration.setAttribute(A_TEMPLATE, dataModel.getTemplateFileLocationDataModel().getFilePath());
configuration.setAttribute(A_ENV_VARS, dataModel.getEnvvarFileLocationDataModel().getFilePath());
configuration.setAttribute(A_CODE_URI, dataModel.getCodeUri());
configuration.setAttribute(A_TIME_OUT, String.valueOf(dataModel.getTimeOut()));
SamAction samAction = dataModel.getSamAction();
configuration.setAttribute(A_ACTION, samAction.getName());
dataModel.getActionDataModel().toAttributeMap().forEach(configuration::setAttribute);
}
@Override
public String getName() {
return "Main";
}
@Override
public Image getImage() {
return LambdaPlugin.getDefault().getImageRegistry().getDescriptor(LambdaPlugin.IMAGE_SAM_LOCAL).createImage();
}
private String getAttribute(ILaunchConfiguration configuration, String name, String defaultValue) {
try {
return configuration.getAttribute(name, defaultValue);
} catch (CoreException ex) {
return defaultValue;
}
}
}
| 7,908 |
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/launching/SamLocalTabGroup.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.launching;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTabGroup;
import org.eclipse.debug.ui.CommonTab;
import org.eclipse.debug.ui.ILaunchConfigurationDialog;
import org.eclipse.debug.ui.ILaunchConfigurationTab;
public class SamLocalTabGroup extends AbstractLaunchConfigurationTabGroup {
@Override
public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
setTabs(new ILaunchConfigurationTab[] {
new SamLocalTab(),
new CommonTab()
});
}
}
| 7,909 |
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/launching/SamLocalPathFinder.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.launching;
import java.io.File;
import java.util.Arrays;
import org.apache.maven.model.Model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.m2e.core.MavenPlugin;
import com.amazonaws.eclipse.core.util.PluginUtils;
public class SamLocalPathFinder {
private static final String[] TEMPLATE_FILES = {
"template.yaml", "template.yml", "serverless.template", "serverless.json", "template.json", "sam.template", "sam.json"
};
private static final String[] ENV_VAR_FILES = {"envvars.json", "envvar.json", "env-vars.json"};
private static final String[] EVENT_FILES = {"s3-event.json", "sns-event.json", "kinesis-event.json", "dynamodb-event.json", "api-event.json", "schedule-event.json"};
public static String findTemplateFile(String projectName) {
return find(projectName, TEMPLATE_FILES);
}
public static String findEnvVarFile(String projectName) {
return find(projectName, ENV_VAR_FILES);
}
public static String findEventFile(String projectName) {
return find(projectName, EVENT_FILES);
}
/**
* Parse the project pom.xml file to generate the location for the build artifact.
*/
public static String findCodeUri(String projectName) {
if (projectName == null || projectName.isEmpty()) {
return "";
}
IFile pomFile = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).getFile("pom.xml");
if (pomFile.exists()) {
try {
Model mavenModel = MavenPlugin.getMavenModelManager().readMavenModel(pomFile);
String artifactId = mavenModel.getArtifactId();
String version = mavenModel.getVersion();
return String.format("./target/%s-%s.jar", artifactId, version);
} catch (CoreException e) {
return "";
}
}
return "";
}
private static String variablePluginReplace(String path) {
try {
return PluginUtils.variablePluginReplace(path);
} catch (CoreException e) {
return path;
}
}
private static boolean fileExists(String path) {
File file = new File(path);
return file.exists() && file.isFile();
}
private static String find(String projectName, String[] candidatePaths) {
if (projectName == null || projectName.isEmpty()) {
return "";
}
return Arrays.stream(candidatePaths)
.map(subpath -> PluginUtils.variablePluginGenerateWorkspacePath(projectName + "/" + subpath))
.filter(path -> fileExists(variablePluginReplace(path)))
.findFirst().orElse("");
}
}
| 7,910 |
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/launching/SamLocalConsoleColorProvider.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.launching;
import org.eclipse.debug.ui.console.ConsoleColorProvider;
import org.eclipse.swt.graphics.Color;
import com.amazonaws.eclipse.lambda.ui.LambdaPluginColors;
/**
* Color for SAM Local terminal output. The default color is red as SAM Local's output
* goes to stderr even they are not actually error messages. We override it to be black.
*/
public class SamLocalConsoleColorProvider extends ConsoleColorProvider {
@Override
public Color getColor(String streamIdentifer) {
// Make the output black.
return LambdaPluginColors.BLACK;
}
}
| 7,911 |
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/launching/SamLocalDelegate.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.launching;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_ACTION;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_CODE_URI;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_DEBUG_PORT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_ENV_VARS;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_EVENT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_HOST;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_LAMBDA_IDENTIFIER;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_MAVEN_GOALS;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_PORT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_PROFILE;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_PROJECT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_REGION;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_SAM;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_TEMPLATE;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_TIME_OUT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.PROCESS_TYPE;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.ILaunchConfigurationDelegate;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.ui.console.IOConsole;
import org.eclipse.ui.console.IOConsoleOutputStream;
import com.amazonaws.eclipse.core.exceptions.AwsActionException;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.core.telemetry.MetricsDataModel;
import com.amazonaws.eclipse.core.util.CliUtil;
import com.amazonaws.eclipse.core.util.MavenBuildLauncher;
import com.amazonaws.eclipse.core.util.PluginUtils;
import com.amazonaws.eclipse.core.util.RemoteDebugLauncher;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.launching.SamLocalExecution.LaunchMode;
import com.amazonaws.eclipse.lambda.project.wizard.model.RunSamLocalDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.model.RunSamLocalDataModel.SamAction;
import com.amazonaws.eclipse.lambda.serverless.Serverless;
import com.amazonaws.eclipse.lambda.serverless.model.transform.ServerlessModel;
import com.amazonaws.eclipse.lambda.ui.LambdaPluginColors;
public class SamLocalDelegate implements ILaunchConfigurationDelegate {
@Override
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
throws CoreException {
MetricsDataModel metricsDataModel = new MetricsDataModel(AwsToolkitMetricType.SAMLOCAL_LAUNCH);
try {
LaunchMode launchMode = LaunchMode.fromValue(mode);
metricsDataModel.addAttribute("LaunchMode", launchMode.getMode());
String projectName = configuration.getAttribute(A_PROJECT, (String) null);
if (projectName == null || projectName.isEmpty()) {
throw new IllegalArgumentException("The project name must be provided!");
}
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
subMonitor.setTaskName("Running Maven build to generate the artifact...");
long startTime = System.currentTimeMillis();
new MavenBuildLauncher(project, configuration.getAttribute(A_MAVEN_GOALS, RunSamLocalDataModel.DEFAULT_MAVEN_GOALS),
subMonitor.newChild(30)).launch();
long endTime = System.currentTimeMillis();
metricsDataModel.addMetric("MavenBuildTimeMilli", (double)(endTime-startTime));
subMonitor.worked(30);
List<String> commandLine = buildSamLocalCommandLine(launchMode, configuration.getAttributes());
Map<String, String> envvar = new HashMap<>();
String regionValue = configuration.getAttribute(A_REGION, RunSamLocalDataModel.DEFAULT_REGION);
envvar.put("AWS_REGION", regionValue);
Process samLocalCliProcess = CliUtil.buildProcess(commandLine, envvar);
Map<String, String> attributes = new HashMap<>();
attributes.put(IProcess.ATTR_PROCESS_TYPE, PROCESS_TYPE);
IProcess samLocalProcess = DebugPlugin.newProcess(launch, samLocalCliProcess, projectName, attributes);
IOConsole samLocalConsole = null;
do {
samLocalConsole = (IOConsole) DebugUITools.getConsole(samLocalProcess);
} while (samLocalConsole == null
&& !subMonitor.isCanceled()
&& !samLocalProcess.isTerminated());
IOConsoleOutputStream samLocalOutputStream = samLocalConsole.newOutputStream();
samLocalOutputStream.setColor(LambdaPluginColors.GREY);
safeWriteToConsole(samLocalOutputStream, "Running command: " + commandLine.stream().collect(Collectors.joining(" ")));
int debugPort = Integer.parseInt(configuration.getAttribute(A_DEBUG_PORT, String.valueOf(RunSamLocalDataModel.DEFAULT_DEBUG_PORT)));
SamAction command = SamAction.fromValue(configuration.getAttribute(A_ACTION, SamAction.INVOKE.getName()));
subMonitor.worked(20);
metricsDataModel.addAttribute("SamLocalCommand", command.getName());
if (command == SamAction.INVOKE) {
try {
waitAndLaunchDebugger(project, launchMode, debugPort, samLocalCliProcess, subMonitor, samLocalOutputStream, 50);
} catch (CoreException e) {
samLocalProcess.terminate();
throw new RuntimeException("Failed to launch Eclipse Debugger", e);
}
} else if (command == SamAction.START_API) {
try {
int invokeTimes = 0;
while (!subMonitor.isCanceled() && !samLocalProcess.isTerminated()) {
waitAndLaunchDebugger(project, launchMode, debugPort, samLocalCliProcess, subMonitor, samLocalOutputStream, 1);
++invokeTimes;
}
metricsDataModel.addMetric("InvokeTimes", (double)invokeTimes);
} catch (CoreException e) {
samLocalProcess.terminate();
throw new RuntimeException("Failed to launch Eclipse Debugger", e);
}
}
if (subMonitor.isCanceled()) {
samLocalProcess.terminate();
}
while (!samLocalProcess.isTerminated()) {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
}
}
safeWriteToConsole(samLocalOutputStream, "SAM Local invocation done.");
subMonitor.done();
AwsAction.publishSucceededAction(metricsDataModel);
} catch (Exception e) {
LambdaPlugin.getDefault().reportException("Failed to launch SAM Local.",
new AwsActionException(AwsToolkitMetricType.SAMLOCAL_LAUNCH.getName(), e.getMessage(), e));
AwsAction.publishFailedAction(metricsDataModel);
}
}
/**
* Wait the target port to be taken by the process and kick off Eclipse Debugger.
*
* @param project The target project the Debugger is running in
* @param mode debug or run mode
* @param debugPort The debug port
* @param samLocalCliProcess SAM Local process
* @param subMonitor {@link SubMonitor} for reporting the progress
* @param outputStream The console output stream for showing the current status
* @param totalWork Total work the Debugger takes
* @throws CoreException
*/
private void waitAndLaunchDebugger(IProject project, LaunchMode mode, int debugPort,
Process samLocalCliProcess, SubMonitor subMonitor, IOConsoleOutputStream outputStream, int totalWork) throws CoreException {
if (mode == LaunchMode.DEBUG) {
String statusUpdateMessage = "Waiting for SAM Local to attach the port " + debugPort;
subMonitor.setTaskName(statusUpdateMessage);
safeWriteToConsole(outputStream, statusUpdateMessage);
}
if (waitForPortBeingTakenByProcess(samLocalCliProcess, debugPort, subMonitor)) {
String statusUpdateMessage = "Running Eclipse Debugger...";
subMonitor.setTaskName(statusUpdateMessage);
safeWriteToConsole(outputStream, statusUpdateMessage);
new RemoteDebugLauncher(project, debugPort, subMonitor.newChild(totalWork)).launch();
subMonitor.worked(totalWork);
}
}
private void safeWriteToConsole(IOConsoleOutputStream outputStream, String content) {
try {
outputStream.write("[AWS Toolkit] " + content + "\n");
} catch (IOException e) {
LambdaPlugin.getDefault().logError("Failed to write to SAM Local console.", e);
}
}
/**
* Create a temporary template file based on the provided configuration map. It modifies the
* template file in A_TEMPLATE with the overriding value of A_CODE_URI and A_TIME_OUT.
*/
private String createTemporaryTemplateFile(Map<String, Object> config) throws CoreException {
String codeUri = (String) config.get(A_CODE_URI);
String timeOut = (String) config.get(A_TIME_OUT);
String project = (String) config.get(A_PROJECT);
String templateFile = (String) config.get(A_TEMPLATE);
String templateFilePath = PluginUtils.variablePluginReplace(templateFile);
try {
ServerlessModel serverlessModel = Serverless.load(templateFilePath);
serverlessModel.getServerlessFunctions().forEach((k, v) -> {
if (codeUri != null && !codeUri.isEmpty()) {
v.setCodeUri(codeUri);
}
v.setTimeout(Integer.parseInt(timeOut));
});
IPath tempTemplate = ResourcesPlugin.getWorkspace().getRoot().getProject(project).getLocation();
String outputPath = tempTemplate.append(".serverless.template").toOSString();
File outputFile = Serverless.write(serverlessModel, outputPath);
outputFile.deleteOnExit();
return outputPath;
} catch (IOException e ) {
// Any error occurs, fall back to the original template file.
return templateFilePath;
}
}
private List<String> buildSamLocalCommandLine(LaunchMode mode, Map<String, Object> config) throws CoreException {
final Set<String> invokeParamSet = new HashSet<>(Arrays.asList(A_TEMPLATE, A_ENV_VARS, A_EVENT, A_PROFILE));
final Set<String> startApiParamSet = new HashSet<>(Arrays.asList(A_TEMPLATE, A_ENV_VARS, A_PROFILE, A_HOST, A_PORT));
if (mode == LaunchMode.DEBUG) {
invokeParamSet.add(A_DEBUG_PORT);
startApiParamSet.add(A_DEBUG_PORT);
}
List<String> commandLine = new ArrayList<>();
commandLine.add(config.get(A_SAM).toString());
commandLine.add("local");
commandLine.add(config.get(A_ACTION).toString());
SamAction samAction = SamAction.fromValue(config.get(A_ACTION).toString());
switch (samAction) {
case INVOKE:
if (config.get(A_LAMBDA_IDENTIFIER) != null) {
commandLine.add(config.get(A_LAMBDA_IDENTIFIER).toString());
}
commandLine = buildCommandLineFromMap(commandLine, config, invokeParamSet);
break;
case START_API:
commandLine = buildCommandLineFromMap(commandLine, config, startApiParamSet);
break;
}
return commandLine;
}
private List<String> buildCommandLineFromMap(List<String> commandLine, Map<String, Object> parameters, Set<String> parameterSet)
throws CoreException {
// Replacing these attributes with actually values from the path placeholder
Set<String> replacableParams = new HashSet<>(Arrays.asList(A_TEMPLATE, A_EVENT, A_ENV_VARS));
for (Entry<String, Object> entry : parameters.entrySet()) {
String key = entry.getKey();
if (!parameterSet.contains(key)) {
continue;
}
String value = parameters.get(key).toString();
if (replacableParams.contains(key)) {
value = PluginUtils.variablePluginReplace(value);
}
commandLine.add("--" + key);
if (key.equals(A_TEMPLATE)) {
value = createTemporaryTemplateFile(parameters);
}
commandLine.add(value);
}
return commandLine;
}
// Wait for the port being take by the specified Process.
// Return true if the port is taken in the given condition, otherwise false.
private boolean waitForPortBeingTakenByProcess(Process process, int portNo, IProgressMonitor monitor) {
long pingIntervalMilli = 100;
while (process.isAlive() && !monitor.isCanceled()) {
try (Socket socket = new Socket("localhost", portNo)) {
return true;
} catch (UnknownHostException e1) {
return false;
} catch (IOException e1) {}
try {
Thread.sleep(pingIntervalMilli);
} catch (InterruptedException e) {}
}
return false;
}
}
| 7,912 |
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/launching/SamLocalConsoleLineTracker.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.launching;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.debug.ui.console.IConsole;
import org.eclipse.debug.ui.console.IConsoleLineTracker;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IRegion;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.IHyperlink;
import com.amazonaws.eclipse.core.util.WorkbenchUtils;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
/**
* Recognize the console URL and convert it as a link to be clickable.
*/
public class SamLocalConsoleLineTracker implements IConsoleLineTracker {
// The pattern accept a four-digit IP address or localhost as a special IP address, with a port number at the end.
private static final String URL_LINK_PATTERN_STRING = "((http|https)://)?"
+ "(((\\d|\\d{2}|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(\\d|\\d{2}|1\\d{2}|2[0-4]\\d|25[0-5])|localhost)"
+ ":(6[0-4]\\d{3}|65[0-4]\\d{2}|655[0-2]\\d|6553[0-5]|[0-5]?\\d{1,5})";
public static final Pattern URL_PATTERN = Pattern.compile(URL_LINK_PATTERN_STRING);
private IConsole console;
@Override
public void init(IConsole console) {
this.console = console;
}
@Override
public void lineAppended(IRegion line) {
try {
int offset = line.getOffset();
int length = line.getLength();
String text = console.getDocument().get(offset, length);
Matcher matcher = URL_PATTERN.matcher(text);
String url = null;
if (matcher.find()) {
url = matcher.group();
offset += matcher.start();
}
if (url != null) {
final String thisUrl = url;
console.addLink(new IHyperlink() {
@Override
public void linkExited() {}
@Override
public void linkEntered() {}
@Override
public void linkActivated() {
try {
WorkbenchUtils.openInternalBrowserAsEditor(new URL(thisUrl), PlatformUI.getWorkbench());
} catch (MalformedURLException e) {
LambdaPlugin.getDefault().logError("Cannot open the URL: " + thisUrl, e);
}
}
}, offset, url.length());
}
} catch (BadLocationException e) {
LambdaPlugin.getDefault().logError("Failed to process the console document.", e);
}
}
@Override
public void dispose() {
}
}
| 7,913 |
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/launching/SamLocalExecution.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.launching;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_PROJECT;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.IDebugModelPresentation;
import org.eclipse.debug.ui.ILaunchGroup;
import org.eclipse.debug.ui.ILaunchShortcut;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.exceptions.AwsActionException;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
public class SamLocalExecution implements ILaunchShortcut {
private static final String SAM_LOCAL_LAUNCH_CONFIGURATION_ID = "com.amazonaws.eclipse.lambda.launching.samLocal";
/**
* Launch SAM Local from project explorer
*/
@Override
public void launch(ISelection selection, String mode) {
if (selection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection = (IStructuredSelection ) selection;
Object firstElement = structuredSelection.getFirstElement();
if (firstElement instanceof IJavaElement) {
launch((IJavaElement)firstElement, LaunchMode.fromValue(mode));
}
}
}
/**
* Launch SAM Local from file editor
*/
@Override
public void launch(IEditorPart editor, String mode) {
IEditorInput editorInput = editor.getEditorInput();
if (editorInput instanceof IFileEditorInput) {
IFile file = ((IFileEditorInput)editorInput).getFile();
IJavaElement element = JavaCore.create(file);
if (element != null) {
launch(element, LaunchMode.fromValue(mode));
}
}
}
/**
* Central place for all entries of invoking SAM Local.
*/
public static void launch(IJavaElement javaElement, LaunchMode mode) {
try {
IProject project = javaElement.getJavaProject().getProject();
ILaunchConfiguration configuration = getLaunchConfiguration(project, mode);
if (configuration == null) {
configuration = createLaunchConfiguration(project, mode);
ILaunchGroup group = DebugUITools.getLaunchGroup(configuration, mode.getMode());
DebugUITools.openLaunchConfigurationDialog(Display.getCurrent().getActiveShell(),
configuration, group.getIdentifier(), null);
} else {
DebugUITools.launch(configuration, mode.getMode());
}
} catch (Exception e) {
LambdaPlugin.getDefault().reportException("Failed to run SAM Locol",
new AwsActionException(AwsToolkitMetricType.SAMLOCAL_LAUNCH.getName(), e.getMessage(), e));
}
}
/**
* Create a new {@link ILaunchConfiguration} for the specified project.
*/
private static ILaunchConfiguration createLaunchConfiguration(IContainer basedir, LaunchMode mode) throws CoreException {
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(SAM_LOCAL_LAUNCH_CONFIGURATION_ID);
String configName = launchManager.generateLaunchConfigurationName("AWS SAM Local " + basedir.getName());
ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, configName);
workingCopy.setAttribute(A_PROJECT, basedir.getName());
return workingCopy.doSave();
}
/**
* Returns an existing {@link ILaunchConfiguration} based on the provided project.
*
* @return The only existing one or the chosen one {@link ILaunchConfiguration}, or null if no one exists.
* @throws CoreException
*/
private static ILaunchConfiguration getLaunchConfiguration(IContainer basedir, LaunchMode mode) throws CoreException {
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType launchConfigurationType = launchManager
.getLaunchConfigurationType(SAM_LOCAL_LAUNCH_CONFIGURATION_ID);
if (launchConfigurationType == null) {
return null;
}
// Scan existing launch configurations
ILaunchConfiguration[] launchConfigurations = launchManager.getLaunchConfigurations(launchConfigurationType);
List<ILaunchConfiguration> matchingConfigs = Arrays.stream(launchConfigurations).filter(config -> {
try {
String projectName = config.getAttribute(A_PROJECT, (String) null);
return projectName != null && projectName.equals(basedir.getName());
} catch (CoreException e) {
return false;
}
}).collect(Collectors.toList());
if (matchingConfigs.size() == 1) {
return matchingConfigs.get(0);
} else if (matchingConfigs.size() > 1) {
IDebugModelPresentation labelProvider = DebugUITools.newDebugModelPresentation();
ElementListSelectionDialog dialog = new ElementListSelectionDialog(
AwsToolkitCore.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(), labelProvider);
dialog.setElements(matchingConfigs.toArray(new ILaunchConfiguration[matchingConfigs.size()]));
dialog.setTitle("Select SAM Local Configuration");
dialog.setMessage("Choose which launch profile to use");
dialog.setMultipleSelection(false);
int result = dialog.open();
labelProvider.dispose();
return result == Window.OK ? (ILaunchConfiguration) dialog.getFirstResult() : null;
}
return null;
}
public static enum LaunchMode {
RUN("run"),
DEBUG("debug"),
;
private final String mode;
private LaunchMode(String mode) {
this.mode = mode;
}
public static LaunchMode fromValue(String mode) {
for (LaunchMode launchMode : LaunchMode.values()) {
if (launchMode.getMode().equals(mode)) {
return launchMode;
}
}
throw new IllegalArgumentException(mode + " is not a valid mode for running AWS SAM Local.");
}
public String getMode() {
return mode;
}
}
}
| 7,914 |
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/dialog/SamLocalGenerateEventDialog.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.dialog;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoProperties;
import org.eclipse.core.databinding.observable.Observables;
import org.eclipse.core.databinding.observable.map.WritableMap;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.SaveAsDialog;
import com.amazonaws.eclipse.core.exceptions.AwsActionException;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.core.telemetry.MetricsDataModel;
import com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory;
import com.amazonaws.eclipse.core.util.CliUtil;
import com.amazonaws.eclipse.core.util.CliUtil.CliProcessTracker;
import com.amazonaws.eclipse.core.widget.ComboViewerComplex;
import com.amazonaws.eclipse.core.widget.TextComplex;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.launching.SamLocalConstants;
import com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil;
/**
* Dialog for generating Lambda handler event json file using SAM Local.
*/
public class SamLocalGenerateEventDialog extends TitleAreaDialog {
private final SamLocalLambdaEventDataModel dataModel = new SamLocalLambdaEventDataModel();
private final DataBindingContext bindingContext;
private ScrolledComposite scrolledComposite;
private Composite composite;
private ComboViewerComplex<SamLocalLambdaEvent> lambdaEventCombo;
public SamLocalGenerateEventDialog(Shell parentShell) {
super(parentShell);
this.bindingContext = new DataBindingContext();
}
public SamLocalLambdaEventDataModel getDataModel() {
return dataModel;
}
@Override
public void create() {
super.create();
setTitle("Generate Lambda event template");
setMessage("Generates Lambda events (e.g. for S3/Kinesis etc) that can be used as the input of the Lambda function.");
}
@Override
protected Control createDialogArea(Composite parent) {
Composite rootComposite = (Composite) super.createDialogArea(parent);
lambdaEventCombo = ComboViewerComplex.<SamLocalLambdaEvent>builder()
.composite(WizardWidgetFactory.newComposite(rootComposite, 1, 2))
.labelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
if (element instanceof SamLocalLambdaEvent) {
return ((SamLocalLambdaEvent) element).presentation;
}
return super.getText(element);
}
})
.pojoObservableValue(PojoProperties.value(SamLocalLambdaEventDataModel.P_EVENT_TYPE).observe(dataModel))
.bindingContext(bindingContext)
.items(Arrays.asList(SamLocalLambdaEvent.values()))
.defaultItem(SamLocalLambdaEvent.S3)
.labelValue("Select event type: ")
.addListeners(e -> onLambdaEventComboSelect())
.build();
Group parameterListGroup = WizardWidgetFactory.newGroup(rootComposite, "Parameter List");
scrolledComposite = new ScrolledComposite(parameterListGroup, SWT.V_SCROLL);
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
GridDataFactory.fillDefaults().grab(true, true).applyTo(scrolledComposite);
composite = new Composite(scrolledComposite, SWT.None);
GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);
scrolledComposite.setContent(composite);
onLambdaEventComboSelect();
return rootComposite;
}
private void onLambdaEventComboSelect() {
for (Control control : composite.getChildren()) {
control.dispose();
}
SamLocalLambdaEvent eventType = dataModel.getEventType();
for (SamLocalEventParameter parameter : eventType.parameterList) {
TextComplex.builder(composite, bindingContext, Observables.observeMapEntry(dataModel.getParameterList(), parameter.name, String.class))
.defaultValue(parameter.defaultValue)
.labelValue(parameter.presentation)
.textMessage(parameter.description)
.build();
}
setMessage(eventType.description);
Shell shell = composite.getShell();
shell.setMinimumSize(getInitialSize());
shell.layout(true, true);
}
@Override
protected void okPressed() {
SaveAsDialog saveAsDialog = new SaveAsDialog(this.getShell());
if (saveAsDialog.open() == Window.OK) {
dataModel.setResultPath(saveAsDialog.getResult());
generateEventFile();
}
super.okPressed();
}
@Override
protected boolean isResizable() {
return true;
}
private void generateEventFile() {
SamLocalLambdaEvent eventType = dataModel.getEventType();
List<String> builder = new ArrayList<>();
builder.add(LambdaPlugin.getDefault().getPreferenceStore().getString(SamLocalConstants.P_SAM_LOCAL_EXECUTABLE));
builder.add("local");
builder.add("generate-event");
builder.add(eventType.commandName);
for (SamLocalEventParameter parameter : eventType.parameterList) {
String value = (String) dataModel.parameterList.get(parameter.name);
if (value == null || value.isEmpty()) {
value = parameter.defaultValue;
}
builder.add("--" + parameter.name);
builder.add(value.replace("\"", "\\\""));
}
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(dataModel.resultPath.segment(0));
File outputFile = project.getLocation().append(dataModel.resultPath.removeFirstSegments(1)).toFile();
MetricsDataModel metricsDataModel = new MetricsDataModel(AwsToolkitMetricType.SAMLOCAL_GENERATE_EVENT);
metricsDataModel.addAttribute("EventType", eventType.presentation);
try {
ByteArrayOutputStream stdErrOutput = new ByteArrayOutputStream();
CliProcessTracker tracker = CliUtil.executeCommand(builder, Collections.emptyMap(),
new FileOutputStream(outputFile), stdErrOutput);
int exitValue = tracker.waitForStream();
FunctionProjectUtil.refreshProject(project);
String stdErr = stdErrOutput.toString();
if (exitValue != 0 && stdErr != null && !stdErr.isEmpty()) {
LambdaPlugin.getDefault().reportException("Failed to generate SAM Local event.",
new AwsActionException(AwsToolkitMetricType.SAMLOCAL_GENERATE_EVENT.getName(), stdErr, null));
AwsAction.publishFailedAction(metricsDataModel);
} else {
AwsAction.publishSucceededAction(metricsDataModel);
}
} catch (IOException e1) {
LambdaPlugin.getDefault().reportException("Failed to generate event json file.", e1);
AwsAction.publishFailedAction(metricsDataModel);
}
}
public static class SamLocalLambdaEventDataModel {
public static final String P_EVENT_TYPE = "eventType";
private SamLocalLambdaEvent eventType;
private WritableMap parameterList = new WritableMap(String.class, String.class);
private IPath resultPath;
public IPath getResultPath() {
return resultPath;
}
public void setResultPath(IPath resultPath) {
this.resultPath = resultPath;
}
public SamLocalLambdaEvent getEventType() {
return eventType;
}
public void setEventType(SamLocalLambdaEvent eventType) {
this.eventType = eventType;
}
public WritableMap getParameterList() {
return parameterList;
}
}
public static enum SamLocalLambdaEvent {
S3("s3", "S3 Event", "Generates a sample Amazon S3 event",
new SamLocalEventParameter("region", "Region", "The region the event should come from (default: \"us-east-1\")", "us-east-1"),
new SamLocalEventParameter("bucket", "Bucket", "The S3 bucket the event should reference (default: \"example-bucket\")", "example-bucket"),
new SamLocalEventParameter("key", "Key", "The S3 key the event should reference (default: \"test/key\")", "test/key")),
SNS("sns", "SNS Event", "Generates a sample Amazon SNS event",
new SamLocalEventParameter("message", "Message", "The SNS message body (default: \"example message\")", "example message"),
new SamLocalEventParameter("topic", "Topic", "The SNS topic (default: \"arn:aws:sns:us-east-1:111122223333:ExampleTopic\")", "arn:aws:sns:us-east-1:111122223333:ExampleTopic"),
new SamLocalEventParameter("subject", "Subject", "The SNS subject (default: \"example subject\")", "example subject")),
KINESIS("kinesis", "Kinesis Event", "Generates a sample Amazon Kinesis event",
new SamLocalEventParameter("region", "AWS Region", "The region the event should come from (default: \"us-east-1\")", "us-east-1"),
new SamLocalEventParameter("partition", "Partition", "The Kinesis partition key (default: \"partitionKey-03\")", "partitionKey-03"),
new SamLocalEventParameter("sequence", "Sequence", "The Kinesis sequence number (default: \"49545115243490985018280067714973144582180062593244200961\")", "49545115243490985018280067714973144582180062593244200961"),
new SamLocalEventParameter("data", "Data", "The Kinesis message payload, with no base64 encoded (default: \"Hello, this is a test 123.\")", "Hello, this is a test 123.")),
DYNAMODB("dynamodb", "DynamoDB Event", "Generates a sample Amazon DynamoDB event",
new SamLocalEventParameter("region", "Region", "The region the event should come from (default: \"us-east-1\")", "us-east-1")),
API("api", "API Gateway Event", "Generates a sample Amazon API Gateway event",
new SamLocalEventParameter("method", "Method", "HTTP method (default: \"POST\")", "POST"),
new SamLocalEventParameter("body", "Body", "HTTP body (default: \"{ \"test\": \"body\"}\")", "{ \"test\": \"body\"}"),
new SamLocalEventParameter("resource", "Resource", "API Gateway resource name (default: \"/{proxy+}\")", "/{proxy+}"),
new SamLocalEventParameter("path", "Path", "HTTP path (default: \"/examplepath\")", "/examplepath")),
SCHEDULE("schedule", "Scheduled Event", "Generates a sample scheduled event",
new SamLocalEventParameter("region", "Region", "The region the event should come from (default: \"us-east-1\")", "us-east-1")),
;
private final String commandName;
private final String presentation;
private final String description;
private final SamLocalEventParameter[] parameterList;
private SamLocalLambdaEvent(String commandName, String presentation, String description, SamLocalEventParameter... eventParameters) {
this.commandName = commandName;
this.presentation = presentation;
this.description = description;
parameterList = eventParameters;
}
}
public static class SamLocalEventParameter {
private final String name;
private final String presentation;
private final String description;
private final String defaultValue;
public SamLocalEventParameter(String name, String presentation, String description, String defaultValue) {
this.name = name;
this.presentation = presentation;
this.description = description;
this.defaultValue = defaultValue;
}
}
}
| 7,915 |
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/project/LambdaFunctionProjectDecorator.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.project;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IType;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata.LambdaFunctionDeploymentMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.ProjectMetadataManager;
/**
* This class decorates the Project Explorer entry for the AWS Lambda Runtime
* classpath container
*/
public class LambdaFunctionProjectDecorator implements ILabelDecorator {
@Override
public Image decorateImage(Image image, Object element) {
// TODO Auto-generated method stub
return null;
}
/**
* Decorate handler class java file with the remote AWS Lambda function name.
*/
@Override
public String decorateText(String text, Object element) {
if (element instanceof ICompilationUnit) {
ICompilationUnit compilationUnit = (ICompilationUnit) element;
IProject project = compilationUnit.getJavaProject().getProject();
if (project == null) {
return null;
}
try {
LambdaFunctionProjectMetadata md = ProjectMetadataManager.loadLambdaProjectMetadata(project);
if (md == null) {
return null;
}
for (IType type : compilationUnit.getTypes()) {
if (md.getHandlerMetadata().containsKey(type.getFullyQualifiedName())) {
LambdaFunctionDeploymentMetadata deployment = md.getHandlerMetadata().get(type.getFullyQualifiedName())
.getDeployment();
return text + " [" + (deployment == null ? "" : deployment.getAwsLambdaFunctionName()) + "]";
}
}
return null;
} catch (Exception e) {
return null;
}
}
return null;
}
@Override
public void dispose() {
// no-op
}
@Override
public boolean isLabelProperty(Object element, String property) {
return true;
}
@Override
public void addListener(ILabelProviderListener listener) {
// no-op
}
@Override
public void removeListener(ILabelProviderListener listener) {
// no-op
}
}
| 7,916 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/listener/LambdaProjectChangeTracker.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.project.listener;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
/**
* Responsible for tracking local changes to all the projects in the current
* workspace
*/
public class LambdaProjectChangeTracker {
private final ConcurrentHashMap<IProject, Boolean> projectDirtyMap = new ConcurrentHashMap<>();
private final IElementChangedListener projectChangeListener = new LambdaProjectElementChangeListener();
public void start() {
JavaCore.addElementChangedListener(projectChangeListener,
ElementChangedEvent.POST_CHANGE);
}
public void stop() {
JavaCore.removeElementChangedListener(projectChangeListener);
}
public void clearDirtyFlags() {
projectDirtyMap.clear();
}
public boolean isProjectDirty(IJavaProject project) {
return isProjectDirty(project.getProject());
}
/**
* @return true if the project is marked as dirty or if the dirty flag is
* never set for this project.
*/
public boolean isProjectDirty(IProject project) {
Boolean dirtyFlag = projectDirtyMap.get(project);
if (dirtyFlag == null) {
return true;
}
return dirtyFlag;
}
public void markProjectAsNotDirty(IProject project) {
updateProjectDirtyFlag(project, false);
}
private void markProjectAsDirty(IProject project) {
updateProjectDirtyFlag(project, true);
}
private void markProjectAsDirty(IJavaProject project) {
markProjectAsDirty(project.getProject());
}
private void updateProjectDirtyFlag(IProject project, boolean dirty) {
projectDirtyMap.put(project, dirty);
LambdaPlugin.getDefault().trace(
"Project [" + project.getName() + "] dirty flag set to "
+ dirty);
}
/**
* A JDT element change listener implementation that marks a project (and
* its upstream dependencies) as dirty whenever an element change is
* detected in the project.
*/
private class LambdaProjectElementChangeListener implements
IElementChangedListener {
@Override
public void elementChanged(ElementChangedEvent event) {
JavaElementDeltaAcceptor.accept(event.getDelta(),
new JavaElementDeltaAcceptor.Visitor() {
@Override
protected boolean visit(IJavaProject project) {
markProjectAsDirty(project);
for (IProject dependent : project.getProject()
.getReferencingProjects()) {
markProjectAsDirty(dependent);
}
return true;
}
});
}
}
}
| 7,917 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/listener/JavaElementDeltaAcceptor.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.project.listener;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
/**
* An acceptor that invokes the given visitor by traversing the incoming
* IJavaElementDelta and all its affected children
*/
class JavaElementDeltaAcceptor {
public static void accept(IJavaElementDelta delta, Visitor visitor) {
if (visitor.visit(delta.getElement())) {
accept(delta.getAffectedChildren(), visitor);
}
}
private static void accept(IJavaElementDelta[] deltas, Visitor visitor) {
for (IJavaElementDelta delta : deltas) {
accept(delta, visitor);
}
}
public static abstract class Visitor {
private boolean visit(IJavaElement element) {
switch (element.getElementType()) {
case IJavaElement.JAVA_MODEL: {
return visit((IJavaModel) element);
}
case IJavaElement.JAVA_PROJECT: {
return visit((IJavaProject) element);
}
case IJavaElement.PACKAGE_FRAGMENT: {
return visit((IPackageFragment) element);
}
case IJavaElement.PACKAGE_FRAGMENT_ROOT: {
return visit((IPackageFragmentRoot) element);
}
case IJavaElement.COMPILATION_UNIT: {
return visit((ICompilationUnit) element);
}
case IJavaElement.CLASS_FILE: {
return visit((IClassFile) element);
}
default:
return true;
}
}
protected boolean visit(IJavaModel model) {
return true;
}
protected boolean visit(IJavaProject project) {
return true;
}
protected boolean visit(IPackageFragment fragment) {
return true;
}
protected boolean visit(IPackageFragmentRoot fragmentRoot) {
return true;
}
protected boolean visit(ICompilationUnit unit) {
return true;
}
protected boolean visit(IClassFile clazz) {
return true;
}
}
}
| 7,918 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/NewLambdaJavaFunctionProjectWizard.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.project.wizard;
import static com.amazonaws.eclipse.core.util.JavaProjectUtils.setDefaultJreToProjectClasspath;
import java.io.File;
import java.net.MalformedURLException;
import org.apache.maven.model.Model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.m2e.core.ui.internal.UpdateMavenProjectJob;
import com.amazonaws.eclipse.core.exceptions.AwsActionException;
import com.amazonaws.eclipse.core.maven.MavenFactory;
import com.amazonaws.eclipse.core.model.MavenConfigurationDataModel;
import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin;
import com.amazonaws.eclipse.core.plugin.AbstractAwsProjectWizard;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.core.util.WorkbenchUtils;
import com.amazonaws.eclipse.core.validator.JavaPackageName;
import com.amazonaws.eclipse.lambda.LambdaAnalytics;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.project.wizard.model.LambdaFunctionWizardDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.page.NewLambdaJavaFunctionProjectWizardPageOne;
import com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil;
public class NewLambdaJavaFunctionProjectWizard extends AbstractAwsProjectWizard {
private static final String DEFAULT_GROUP_ID = "com.amazonaws.lambda";
private static final String DEFAULT_ARTIFACT_ID = "demo";
private static final String DEFAULT_VERSION = "1.0.0";
private static final String DEFAULT_PACKAGE_NAME = MavenFactory.assumePackageName(DEFAULT_GROUP_ID, DEFAULT_ARTIFACT_ID);
private final LambdaFunctionWizardDataModel dataModel = new LambdaFunctionWizardDataModel();
private NewLambdaJavaFunctionProjectWizardPageOne pageOne;
private IProject project;
@Override
public void addPages() {
if (pageOne == null) {
pageOne = new NewLambdaJavaFunctionProjectWizardPageOne(dataModel);
}
addPage(pageOne);
}
public NewLambdaJavaFunctionProjectWizard() {
super("New AWS Lambda Maven Project");
initDataModel();
}
@Override
protected IStatus doFinish(IProgressMonitor monitor) {
LambdaAnalytics.trackNewProjectAttributes(dataModel);
final String projectName = dataModel.getProjectNameDataModel().getProjectName();
final Model mavenModel = getModel();
File readmeFile = null;
try {
savePreferences(dataModel, LambdaPlugin.getDefault().getPreferenceStore());
final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
project = root.getProject(projectName);
try {
MavenFactory.createMavenProject(project, mavenModel, monitor);
IJavaProject javaProject = JavaCore.create(project);
setDefaultJreToProjectClasspath(javaProject, monitor);
} catch (Exception e) {
LambdaPlugin.getDefault().reportException(
"Failed to create AWS Lambda Maven Project.",
new AwsActionException(AwsToolkitMetricType.LAMBDA_NEW_LAMBDA_PROJECT_WIZARD.getName(), e.getMessage(), e));
}
FunctionProjectUtil.createLambdaBlueprintProject(project, dataModel);
if (dataModel.isShowReadmeFile()) {
readmeFile = FunctionProjectUtil.emitLambdaProjectReadme(project, dataModel.getLambdaFunctionDataModel());
}
FunctionProjectUtil.refreshProject(project);
new UpdateMavenProjectJob(new IProject[]{project}).schedule();
} catch (Exception e) {
LambdaAnalytics.trackProjectCreationFailed();
LambdaPlugin.getDefault().reportException("Failed to create new Lambda project", e);
}
LambdaAnalytics.trackProjectCreationSucceeded();
IFile handlerClass = findHandlerClassFile(project, dataModel);
WorkbenchUtils.selectAndReveal(handlerClass, workbench); // show in explorer
WorkbenchUtils.openFileInEditor(handlerClass, workbench); // show in editor
if (readmeFile != null) {
try {
WorkbenchUtils.openInternalBrowserAsEditor(readmeFile.toURI().toURL(), workbench);
} catch (MalformedURLException e) {
LambdaPlugin.getDefault().logWarning(
"Failed to open README.html for the new Lambda project", e);
}
}
return Status.OK_STATUS;
}
// Use this basic Maven model to create a simple Maven project.
private Model getModel() {
Model model = new Model();
String groupId = dataModel.getMavenConfigurationDataModel().getGroupId();
String artifactId = dataModel.getMavenConfigurationDataModel().getArtifactId();
model.setModelVersion(MavenFactory.getMavenModelVersion());
model.setGroupId(groupId);
model.setArtifactId(artifactId);
model.setVersion(MavenFactory.getMavenModelVersion());
return model;
}
@Override
public boolean performCancel() {
LambdaAnalytics.trackProjectCreationCanceled();
return true;
}
@Override
protected void initDataModel() {
MavenConfigurationDataModel mavenDataModel = dataModel.getMavenConfigurationDataModel();
// Bind the package name property from the maven config model to Lambda config model to show the template code changes in the preview.
mavenDataModel.addPropertyChangeListener((e) -> {
dataModel.getLambdaFunctionDataModel().setPackageName(mavenDataModel.getPackageName());
});
mavenDataModel.setGroupId(DEFAULT_GROUP_ID);
mavenDataModel.setArtifactId(DEFAULT_ARTIFACT_ID);
mavenDataModel.setVersion(DEFAULT_VERSION);
mavenDataModel.setPackageName(DEFAULT_PACKAGE_NAME);
dataModel.setShowReadmeFile(LambdaPlugin.getDefault().getPreferenceStore()
.getBoolean(LambdaPlugin.PREF_K_SHOW_README_AFTER_CREATE_NEW_PROJECT));
}
@Override
protected String getJobTitle() {
return "Creating AWS Lambda Maven Project";
}
private static IFile findHandlerClassFile(IProject project,
LambdaFunctionWizardDataModel dataModel) {
IPath handlerPath = new Path(MavenFactory.getMavenSourceFolder());
JavaPackageName handlerPackage = JavaPackageName.parse(
dataModel.getLambdaFunctionDataModel().getPackageName());
for (String component : handlerPackage.getComponents()) {
handlerPath = handlerPath.append(component);
}
handlerPath = handlerPath.append(dataModel.getLambdaFunctionDataModel().getClassName()
+ ".java");
return project.getFile(handlerPath);
}
private static void savePreferences(
LambdaFunctionWizardDataModel dataModel,
IPreferenceStore prefStore) {
prefStore.setValue(
LambdaPlugin.PREF_K_SHOW_README_AFTER_CREATE_NEW_PROJECT,
dataModel.isShowReadmeFile());
}
@Override
protected AbstractAwsPlugin getPlugin() {
return LambdaPlugin.getDefault();
}
}
| 7,919 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/NewLambdaFunctionWizard.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.project.wizard;
import static com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil.refreshProject;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.ui.wizards.NewElementWizard;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.lambda.LambdaAnalytics;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.project.wizard.model.LambdaFunctionWizardDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.page.NewLambdaFunctionWizardPage;
import com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil;
@SuppressWarnings("restriction")
public class NewLambdaFunctionWizard extends NewElementWizard implements INewWizard {
private final LambdaFunctionWizardDataModel dataModel = new LambdaFunctionWizardDataModel();
private NewLambdaFunctionWizardPage pageOne;
@Override
public void addPages() {
super.addPages();
if (pageOne == null) {
pageOne = new NewLambdaFunctionWizardPage(dataModel);
pageOne.setWizard(this);
pageOne.init(getSelection());
}
addPage(pageOne);
}
@Override
protected void finishPage(IProgressMonitor monitor)
throws InterruptedException, CoreException {
final IProject currentProject = getCurrentProject();
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
try {
FunctionProjectUtil.createLambdaHandler(currentProject, dataModel.getLambdaFunctionDataModel());
refreshProject(currentProject);
} catch (Exception e) {
LambdaAnalytics.trackLambdaFunctionCreationFailed();
StatusManager.getManager().handle(
new Status(IStatus.ERROR, LambdaPlugin.PLUGIN_ID,
"Failed to create new Lambda function",
e),
StatusManager.SHOW);
return;
}
LambdaAnalytics.trackLambdaFunctionCreationSucceeded();
try {
IResource handlerClass = pageOne.getModifiedResource();
selectAndReveal(handlerClass); // show in explorer
openResource((IFile) handlerClass);
} catch (Exception e) {
LambdaPlugin.getDefault().logWarning(
"Failed to open the handler class", e);
}
}
});
}
@Override
public IJavaElement getCreatedElement() {
return pageOne.getCreatedType();
}
@Override
public boolean performCancel() {
LambdaAnalytics.trackLambdaFunctionCreationCanceled();
return true;
}
private IProject getCurrentProject() {
return pageOne.getJavaProject().getProject();
}
}
| 7,920 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/NewServerlessProjectWizard.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.project.wizard;
import static com.amazonaws.eclipse.core.util.JavaProjectUtils.setDefaultJreToProjectClasspath;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.maven.model.Model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.m2e.core.ui.internal.UpdateMavenProjectJob;
import com.amazonaws.eclipse.core.exceptions.AwsActionException;
import com.amazonaws.eclipse.core.maven.MavenFactory;
import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin;
import com.amazonaws.eclipse.core.plugin.AbstractAwsProjectWizard;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.core.util.WorkbenchUtils;
import com.amazonaws.eclipse.core.validator.JavaPackageName;
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.template.CodeTemplateManager;
import com.amazonaws.eclipse.lambda.project.wizard.model.NewServerlessProjectDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.page.NewServerlessProjectWizardPageOne;
import com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil;
import com.amazonaws.eclipse.lambda.serverless.template.ServerlessHandlerTemplateData;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import freemarker.template.TemplateException;
public class NewServerlessProjectWizard extends AbstractAwsProjectWizard {
private static final String DEFAULT_GROUP_ID = "com.serverless";
private static final String DEFAULT_ARTIFACT_ID = "demo";
private static final String DEFAULT_VERSION = "1.0.0";
private static final String DEFAULT_PACKAGE_NAME = MavenFactory.assumePackageName(DEFAULT_GROUP_ID, DEFAULT_ARTIFACT_ID);
private final NewServerlessProjectDataModel dataModel = new NewServerlessProjectDataModel();
private NewServerlessProjectWizardPageOne pageOne;
private IProject project;
@Override
public void addPages() {
if (pageOne == null) {
pageOne = new NewServerlessProjectWizardPageOne(dataModel);
}
addPage(pageOne);
}
public NewServerlessProjectWizard() {
super("New AWS Serverless Maven Project");
initDataModel();
}
@Override
protected String getJobTitle() {
return "Creating AWS Serverless Maven Project";
}
@Override
protected IStatus doFinish(IProgressMonitor monitor) {
LambdaAnalytics.trackServerlessProjectSelection(dataModel);
final String projectName = dataModel.getProjectNameDataModel().getProjectName();
final Model mavenModel = getModel();
File readmeFile = null;
final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
project = root.getProject(projectName);
try {
MavenFactory.createMavenProject(project, mavenModel, monitor);
IJavaProject javaProject = JavaCore.create(project);
setDefaultJreToProjectClasspath(javaProject, monitor);
} catch (Exception e) {
LambdaPlugin.getDefault().reportException(
"Failed to create AWS Serverless Maven Project.",
new AwsActionException(AwsToolkitMetricType.LAMBDA_NEW_SERVERLESS_PROJECT_WIZARD.getName(), e.getMessage(), e));
}
try {
FunctionProjectUtil.createServerlessBlueprintProject(project, dataModel);
readmeFile = FunctionProjectUtil.emitServerlessReadme(project, dataModel);
FunctionProjectUtil.refreshProject(project);
new UpdateMavenProjectJob(new IProject[]{project}).schedule();
} catch (Exception e) {
LambdaAnalytics.trackServerlessProjectCreationFailed();
LambdaPlugin.getDefault().reportException("Failed to create new Serverless project",
new AwsActionException(AwsToolkitMetricType.LAMBDA_NEW_SERVERLESS_PROJECT_WIZARD.getName(), e.getMessage(), e));
}
LambdaAnalytics.trackServerlessProjectCreationSucceeded();
saveMetadata();
try {
IFile handlerClass = findHandlerClassFile(project, dataModel);
WorkbenchUtils.selectAndReveal(handlerClass, workbench); // show in explorer
WorkbenchUtils.openFileInEditor(handlerClass, workbench); // show in editor
if (readmeFile != null) {
WorkbenchUtils.openInternalBrowserAsEditor(readmeFile.toURI().toURL(), workbench);
}
} catch (Exception e) {
LambdaPlugin.getDefault().logWarning(
"Failed to open the start up file.", e);
}
return Status.OK_STATUS;
}
@Override
public boolean performCancel() {
LambdaAnalytics.trackServerlessProjectCreationCanceled();
return true;
}
private Model getModel() {
Model model = new Model();
model.setModelVersion(MavenFactory.getMavenModelVersion());
model.setGroupId(dataModel.getMavenConfigurationDataModel().getGroupId());
model.setArtifactId(dataModel.getMavenConfigurationDataModel().getArtifactId());
model.setVersion(MavenFactory.getMavenModelVersion());
return model;
}
private static IFile findHandlerClassFile(IProject project,
NewServerlessProjectDataModel dataModel)
throws JsonParseException, JsonMappingException, IOException, TemplateException {
IPath handlerPath = new Path("");
List<ServerlessHandlerTemplateData> templates = dataModel.getServerlessHandlerTemplateData();
if (templates == null || templates.isEmpty()) {
handlerPath = handlerPath.append(CodeTemplateManager.SAM_FILE_NAME);
} else {
ServerlessHandlerTemplateData template = templates.get(0);
handlerPath = handlerPath.append(MavenFactory.getMavenSourceFolder());
JavaPackageName handlerPackage = JavaPackageName.parse(template.getPackageName());
for (String component : handlerPackage.getComponents()) {
handlerPath = handlerPath.append(component);
}
handlerPath = handlerPath.append(template.getClassName() + ".java");
}
return project.getFile(handlerPath);
}
@Override
protected void initDataModel() {
dataModel.getMavenConfigurationDataModel().setGroupId(DEFAULT_GROUP_ID);
dataModel.getMavenConfigurationDataModel().setArtifactId(DEFAULT_ARTIFACT_ID);
dataModel.getMavenConfigurationDataModel().setVersion(DEFAULT_VERSION);
dataModel.getMavenConfigurationDataModel().setPackageName(DEFAULT_PACKAGE_NAME);
}
private void saveMetadata() {
ServerlessProjectMetadata metadata = new ServerlessProjectMetadata();
metadata.setPackagePrefix(dataModel.getMavenConfigurationDataModel().getPackageName());
try {
ProjectMetadataManager.saveServerlessProjectMetadata(project, metadata);
} catch (IOException e) {
LambdaPlugin.getDefault().logError(e.getMessage(), e);
}
}
@Override
protected AbstractAwsPlugin getPlugin() {
return LambdaPlugin.getDefault();
}
}
| 7,921 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/handler/NewLambdaJavaFunctionProjectHandler.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.project.wizard.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.lambda.project.wizard.NewLambdaJavaFunctionProjectWizard;
public class NewLambdaJavaFunctionProjectHandler extends AbstractHandler {
@Override
@SuppressWarnings("restriction")
public Object execute(ExecutionEvent event) throws ExecutionException {
NewLambdaJavaFunctionProjectWizard newWizard = new NewLambdaJavaFunctionProjectWizard();
newWizard.init(PlatformUI.getWorkbench(), null);
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard);
return dialog.open();
}
}
| 7,922 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/handler/NewLambdaFunctionHandler.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.project.wizard.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.lambda.project.wizard.NewLambdaFunctionWizard;
public class NewLambdaFunctionHandler extends AbstractHandler {
@Override
@SuppressWarnings("restriction")
public Object execute(ExecutionEvent event) throws ExecutionException {
NewLambdaFunctionWizard newWizard = new NewLambdaFunctionWizard();
newWizard.init(PlatformUI.getWorkbench(), null);
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard);
return dialog.open();
}
}
| 7,923 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/handler/NewServerlessProjectHandler.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.project.wizard.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.lambda.project.wizard.NewServerlessProjectWizard;
public class NewServerlessProjectHandler extends AbstractHandler{
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
NewServerlessProjectWizard newWizard = new NewServerlessProjectWizard();
newWizard.init(PlatformUI.getWorkbench(), null);
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard);
return dialog.open();
}
}
| 7,924 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/page/NewServerlessProjectWizardPageOne.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.project.wizard.page;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newSashForm;
import static com.amazonaws.eclipse.lambda.project.wizard.model.NewServerlessProjectDataModel.P_USE_BLUEPRINT;
import static com.amazonaws.eclipse.lambda.project.wizard.model.NewServerlessProjectDataModel.P_USE_SERVERLESS_TEMPLATE_FILE;
import java.util.Iterator;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.observable.ChangeEvent;
import org.eclipse.core.databinding.observable.IChangeListener;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import com.amazonaws.eclipse.core.ui.ImportFileComposite;
import com.amazonaws.eclipse.core.ui.MavenConfigurationComposite;
import com.amazonaws.eclipse.core.ui.ProjectNameComposite;
import com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory;
import com.amazonaws.eclipse.core.widget.RadioButtonComplex;
import com.amazonaws.eclipse.lambda.blueprint.BlueprintsProvider;
import com.amazonaws.eclipse.lambda.project.wizard.model.NewServerlessProjectDataModel;
import com.amazonaws.eclipse.lambda.serverless.ui.FormBrowser;
import com.amazonaws.eclipse.lambda.serverless.validator.ServerlessTemplateFilePathValidator;
public class NewServerlessProjectWizardPageOne extends WizardPage {
private static final String PAGE_NAME = NewServerlessProjectWizardPageOne.class.getName();
private final NewServerlessProjectDataModel dataModel;
private final DataBindingContext bindingContext;
private final AggregateValidationStatus aggregateValidationStatus;
//Composite modules in this page.
private ProjectNameComposite projectNameComposite;
private MavenConfigurationComposite mavenConfigurationComposite;
private ImportFileComposite importFileComposite;
private TableViewer blueprintSelectionViewer;
private FormBrowser descriptionBrowser;
private RadioButtonComplex useBlueprintButtonComplex;
private RadioButtonComplex useServerlessTemplateButtonComplex;
public NewServerlessProjectWizardPageOne(NewServerlessProjectDataModel dataModel) {
super(PAGE_NAME);
setTitle("Create a new Serverless Java project");
setDescription("You can create a new Serverless Java project either from a Blueprint "
+ "or an existing Serverless template file.");
this.dataModel = dataModel;
this.bindingContext = new DataBindingContext();
this.aggregateValidationStatus = new AggregateValidationStatus(
bindingContext, AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent arg0) {
populateValidationStatus();
}
});
}
@Override
public void createControl(final Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
createProjectNameComposite(composite);
createMavenConfigurationComposite(composite);
createUseBlueprintButtonSection(composite);
createBlueprintsSelectionSection(composite);
createUseServerlessTemplateButtonSection(composite);
createServerlessTemplateImportSection(composite);
initialize();
setControl(composite);
}
protected void createProjectNameComposite(Composite composite) {
projectNameComposite = new ProjectNameComposite(
composite, bindingContext, dataModel.getProjectNameDataModel());
}
protected void createMavenConfigurationComposite(Composite composite) {
Group group = WizardWidgetFactory.newGroup(composite, "Maven Configuration");
mavenConfigurationComposite = new MavenConfigurationComposite(
group, bindingContext, dataModel.getMavenConfigurationDataModel());
}
private void initialize() {
onBlueprintSelectionViewerSelectionChange();
onSelectBlueprintButtonSelect();
}
private void createUseBlueprintButtonSection(Composite parent) {
useBlueprintButtonComplex = RadioButtonComplex.builder()
.composite(parent)
.dataBindingContext(bindingContext)
.pojoObservableValue(PojoObservables.observeValue(dataModel, P_USE_BLUEPRINT))
.labelValue("Select a Blueprint:")
.defaultValue(dataModel.isUseBlueprint())
.selectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onSelectBlueprintButtonSelect();
}
})
.build();
}
private void createUseServerlessTemplateButtonSection(Composite parent) {
useServerlessTemplateButtonComplex = RadioButtonComplex.builder()
.composite(parent)
.dataBindingContext(bindingContext)
.pojoObservableValue(PojoObservables.observeValue(dataModel, P_USE_SERVERLESS_TEMPLATE_FILE))
.labelValue("Select a Serverless template file:")
.defaultValue(dataModel.isUseServerlessTemplateFile())
.selectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onSelectServerlessTemplateButtonSelect();
}
})
.build();
}
private void createBlueprintsSelectionSection(Composite parent) {
SashForm sashForm = newSashForm(parent, 1, 2);
blueprintSelectionViewer = new TableViewer(sashForm, SWT.BORDER);
blueprintSelectionViewer.setContentProvider(new ArrayContentProvider());
blueprintSelectionViewer.setInput(BlueprintsProvider.getServerlessBlueprintDisplayNames());
ISelection selection = new StructuredSelection(dataModel.getBlueprintName());
blueprintSelectionViewer.setSelection(selection, true);
blueprintSelectionViewer.addSelectionChangedListener(new ISelectionChangedListener(){
@Override
public void selectionChanged(SelectionChangedEvent event) {
onBlueprintSelectionViewerSelectionChange();
}
});
descriptionBrowser = new FormBrowser(SWT.BORDER | SWT.V_SCROLL);
descriptionBrowser.setText("");
descriptionBrowser.createControl(sashForm);
Control c = descriptionBrowser.getControl();
GridData gd = new GridData(GridData.FILL_BOTH);
c.setLayoutData(gd);
}
private void setBlueprintSelectionSectionEnabled(boolean enabled) {
blueprintSelectionViewer.getTable().setEnabled(enabled);
descriptionBrowser.getControl().setEnabled(enabled);
}
private void onSelectBlueprintButtonSelect() {
setBlueprintSelectionSectionEnabled(true);
setServerlessTemplateImportSectionEnabled(false);
runValidators();
}
private void onSelectServerlessTemplateButtonSelect() {
setBlueprintSelectionSectionEnabled(false);
setServerlessTemplateImportSectionEnabled(true);
runValidators();
}
private void onBlueprintSelectionViewerSelectionChange() {
IStructuredSelection selection = (IStructuredSelection) blueprintSelectionViewer.getSelection();
String blueprint = (String)selection.getFirstElement();
dataModel.setBlueprintName(blueprint);
descriptionBrowser.setText(dataModel.getSelectedBlueprint().getDescription());
}
private void createServerlessTemplateImportSection(Composite parent) {
importFileComposite = ImportFileComposite.builder(parent, bindingContext, dataModel.getImportFileDataModel())
.filePathValidator(new ServerlessTemplateFilePathValidator())
.build();
}
private void setServerlessTemplateImportSectionEnabled(boolean enabled) {
importFileComposite.setEnabled(enabled);
}
private void populateValidationStatus() {
IStatus status = getValidationStatus();
if (status == null) return;
if (status.getSeverity() == IStatus.OK) {
this.setErrorMessage(null);
super.setPageComplete(true);
} else {
setErrorMessage(status.getMessage());
super.setPageComplete(false);
}
}
private IStatus getValidationStatus() {
if (aggregateValidationStatus == null) return null;
Object value = aggregateValidationStatus.getValue();
if (!(value instanceof IStatus)) return null;
return (IStatus)value;
}
private void runValidators() {
Iterator<?> iterator = bindingContext.getBindings().iterator();
while (iterator.hasNext()) {
Binding binding = (Binding)iterator.next();
binding.updateTargetToModel();
}
}
}
| 7,925 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/page/NewLambdaJavaFunctionProjectWizardPageOne.java | /*
* Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.eclipse.lambda.project.wizard.page;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup;
import static com.amazonaws.eclipse.lambda.project.wizard.model.LambdaFunctionWizardDataModel.P_SHOW_README_FILE;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.observable.ChangeEvent;
import org.eclipse.core.databinding.observable.IChangeListener;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import com.amazonaws.eclipse.core.maven.MavenFactory;
import com.amazonaws.eclipse.core.ui.MavenConfigurationComposite;
import com.amazonaws.eclipse.core.ui.ProjectNameComposite;
import com.amazonaws.eclipse.core.widget.CheckboxComplex;
import com.amazonaws.eclipse.lambda.project.wizard.model.LambdaFunctionWizardDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.util.LambdaFunctionComposite;
public class NewLambdaJavaFunctionProjectWizardPageOne extends WizardPage {
private static final String PAGE_NAME = NewLambdaJavaFunctionProjectWizardPageOne.class.getName();
private final LambdaFunctionWizardDataModel dataModel;
private final DataBindingContext dataBindingContext;
private final AggregateValidationStatus aggregateValidationStatus;
// Composite modules in this page.
private ProjectNameComposite projectNameComposite;
private MavenConfigurationComposite mavenConfigurationComposite;
private LambdaFunctionComposite lambdaFunctionComposite;
private CheckboxComplex showReadmeFileComplex;
private ModifyListener mavenModifyListener = new ModifyListener() {
@Override
public void modifyText(ModifyEvent arg0) {
onMavenConfigurationChange();
}
};
public NewLambdaJavaFunctionProjectWizardPageOne(LambdaFunctionWizardDataModel dataModel) {
super(PAGE_NAME);
setTitle("Create a new AWS Lambda Java project");
setDescription("Create a new AWS Lambda Java project in the workspace");
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(final Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
createProjectNameComposite(composite);
createMavenConfigurationComposite(composite);
createLambdaFunctionComposite(composite);
createShowReadmeFileCheckBox(composite);
setControl(composite);
}
@Override
public void dispose() {
lambdaFunctionComposite.dispose();
super.dispose();
}
protected void createProjectNameComposite(Composite composite) {
projectNameComposite = new ProjectNameComposite(
composite, dataBindingContext, dataModel.getProjectNameDataModel());
}
protected void createMavenConfigurationComposite(Composite composite) {
Group group = newGroup(composite, "Maven configuration");
mavenConfigurationComposite = new MavenConfigurationComposite(
group, dataBindingContext, dataModel.getMavenConfigurationDataModel());
}
protected void createLambdaFunctionComposite(Composite composite) {
lambdaFunctionComposite = new LambdaFunctionComposite(
composite, dataModel.getLambdaFunctionDataModel(), dataBindingContext);
lambdaFunctionComposite.createClassNameControl();
lambdaFunctionComposite.createInputTypeControl();
lambdaFunctionComposite.createSeparator();
lambdaFunctionComposite.createHandlerSourcePreview();
lambdaFunctionComposite.initialize();
}
public void createShowReadmeFileCheckBox(Composite composite) {
showReadmeFileComplex = CheckboxComplex.builder()
.composite(composite)
.dataBindingContext(dataBindingContext)
.pojoObservableValue(PojoObservables.observeValue(dataModel, P_SHOW_README_FILE))
.labelValue("Show README guide after creating the project")
.defaultValue(dataModel.isShowReadmeFile())
.build();
}
private void populateValidationStatus() {
IStatus status = getValidationStatus();
if (status == null) return;
if (status.getSeverity() == IStatus.OK) {
this.setErrorMessage(null);
super.setPageComplete(true);
} else {
setErrorMessage(status.getMessage());
super.setPageComplete(false);
}
}
private IStatus getValidationStatus() {
if (aggregateValidationStatus == null) return null;
Object value = aggregateValidationStatus.getValue();
if (!(value instanceof IStatus)) return null;
return (IStatus)value;
}
private void onMavenConfigurationChange() {
if (lambdaFunctionComposite != null) {
String groupId = dataModel.getMavenConfigurationDataModel().getGroupId();
String artifactId = dataModel.getMavenConfigurationDataModel().getArtifactId();
lambdaFunctionComposite.getPackageNameComplex().setText(MavenFactory.assumePackageName(groupId, artifactId));
}
}
} | 7,926 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/page/NewLambdaFunctionWizardPage.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.project.wizard.page;
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.jdt.core.IJavaElement;
import org.eclipse.jdt.ui.wizards.NewTypeWizardPage;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import com.amazonaws.eclipse.lambda.project.wizard.model.LambdaFunctionWizardDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.util.LambdaFunctionComposite;
public class NewLambdaFunctionWizardPage extends NewTypeWizardPage {
private final static String PAGE_NAME = "NewLambdaFunctionWizardPage";
private final LambdaFunctionWizardDataModel dataModel;
private final DataBindingContext dataBindingContext;
private final AggregateValidationStatus aggregateValidationStatus;
private LambdaFunctionComposite lambdaFunctionComposite;
public NewLambdaFunctionWizardPage(LambdaFunctionWizardDataModel dataModel) {
super(true, PAGE_NAME);
setTitle("Create a new AWS Lambda function");
setDescription("Create a new AWS Lambda function in the workspace");
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();
}
});
}
public void init(IStructuredSelection selection) {
IJavaElement jelem = getInitialJavaElement(selection);
initContainerPage(jelem);
initTypePage(jelem);
}
private void doStatusUpdate() {
// update data model
dataModel.getLambdaFunctionDataModel().setPackageName(getPackageText());
dataModel.getLambdaFunctionDataModel().setClassName(getTypeName());
// the mode severe status will be displayed and the OK button enabled/disabled.
updateStatus(getValidationStatus());
}
@Override
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
doStatusUpdate();
}
@Override
public void createControl(final Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
// Reuse the project name and package control of the system Java New Type wizard
createProjectPackageClassNameControls(composite);
createLambdaFunctionComposite(composite);
setControl(composite);
doStatusUpdate();
}
private void createProjectPackageClassNameControls(Composite composite) {
Composite containerComposite = new Composite(composite, SWT.NONE);
containerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
int nColumns = 4;
GridLayout layout = new GridLayout();
layout.numColumns = nColumns;
layout.marginHeight = 10;
layout.marginWidth = 10;
containerComposite.setLayout(layout);
createContainerControls(containerComposite, nColumns);
createPackageControls(containerComposite, nColumns);
createTypeNameControls(containerComposite, nColumns);
}
private void createLambdaFunctionComposite(Composite composite) {
lambdaFunctionComposite = new LambdaFunctionComposite(
composite, dataModel.getLambdaFunctionDataModel(), dataBindingContext);
lambdaFunctionComposite.createInputTypeControl();
lambdaFunctionComposite.createSeparator();
lambdaFunctionComposite.createHandlerSourcePreview();
lambdaFunctionComposite.initialize();
}
@Override
public void dispose() {
lambdaFunctionComposite.dispose();
super.dispose();
}
private void populateValidationStatus() {
IStatus[] statuses = getValidationStatus();
for (IStatus status : statuses) {
if (status == null) continue;
else if (status.getSeverity() == IStatus.OK) {
this.setErrorMessage(null);
super.setPageComplete(true);
} else if (status.getSeverity() == IStatus.ERROR) {
setErrorMessage(status.getMessage());
super.setPageComplete(false);
break;
}
}
}
private IStatus[] getValidationStatus() {
Object value = aggregateValidationStatus.getValue();
IStatus aggregateStatus = (IStatus) value;
// status of all used components
return new IStatus[] {
fContainerStatus,
fPackageStatus,
fTypeNameStatus,
aggregateStatus
};
}
}
| 7,927 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/page | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/page/validator/StackNameValidator.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.project.wizard.page.validator;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import com.amazonaws.util.StringUtils;
public class StackNameValidator implements IValidator {
public String message;
private static final String PATTERN = "^[a-zA-Z]([a-zA-Z\\-0-9])*";
@Override
public IStatus validate(Object value) {
String s = (String)value;
if (StringUtils.isNullOrEmpty(s)) {
return ValidationStatus.error("The stack name must be provided!");
}
s = s.trim();
if (s.matches(PATTERN)) {
return ValidationStatus.ok();
} else {
return ValidationStatus.error("Must contain only letters, numbers, dashes and start with an alpha character.");
}
}
}
| 7,928 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/util/LambdaFunctionComposite.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.project.wizard.util;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newFillingLabel;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLink;
import static com.amazonaws.eclipse.lambda.model.LambdaFunctionDataModel.P_CLASS_NAME;
import static com.amazonaws.eclipse.lambda.model.LambdaFunctionDataModel.P_INPUT_TYPE;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoProperties;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer;
import org.eclipse.jdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.IJavaPartitions;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import com.amazonaws.eclipse.core.widget.ComboComplex;
import com.amazonaws.eclipse.core.widget.TextComplex;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
import com.amazonaws.eclipse.lambda.LambdaConstants;
import com.amazonaws.eclipse.lambda.blueprint.BlueprintsProvider;
import com.amazonaws.eclipse.lambda.blueprint.LambdaBlueprint;
import com.amazonaws.eclipse.lambda.blueprint.LambdaBlueprintsConfig;
import com.amazonaws.eclipse.lambda.model.LambdaFunctionDataModel;
import com.amazonaws.eclipse.lambda.project.template.CodeTemplateManager;
import com.amazonaws.eclipse.lambda.project.template.data.LambdaBlueprintTemplateData;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@SuppressWarnings("restriction")
public class LambdaFunctionComposite {
private final Composite parentComposite;
private final LambdaFunctionDataModel dataModel;
private final LambdaBlueprintsConfig lambdaBlueprintConfig;
private final DataBindingContext dataBindingContext;
private TextComplex packageNameComplex;
private TextComplex classNameComplex;
private ComboComplex inputTypeComplex;
private Link handlerTypeDescriptionLink;
private JavaSourceViewer sourcePreview;
private Document sourcePreviewDocument;
private Group group;
private Composite inputComposite;
public LambdaFunctionComposite(Composite parentComposite,
LambdaFunctionDataModel dataModel, DataBindingContext dataBindingContext) {
this.parentComposite = parentComposite;
this.dataModel = dataModel;
this.dataBindingContext = dataBindingContext;
this.lambdaBlueprintConfig = BlueprintsProvider.provideLambdaBlueprints();
createControl();
}
public void createControl() {
group = newGroup(parentComposite, "Lambda Function Handler");
GridLayout groupLayout = new GridLayout(1, true);
groupLayout.marginWidth = 15;
group.setLayout(groupLayout);
String description =
"Each Lambda function must specify a handler class " +
"which the service will use as the entry point to begin execution.";
setItalicFont(newLink(group, LambdaConstants.webLinkListener,
description + " <a href=\"" +
LambdaConstants.LAMBDA_JAVA_HANDLER_DOC_URL +
"\">Learn more</a> about Lambda Java function handler.",
1));
inputComposite = new Composite(group, SWT.NONE);
inputComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
GridLayout inputCompLayout = new GridLayout(3, true);
inputCompLayout.marginHeight = 10;
inputCompLayout.marginWidth = 10;
inputComposite.setLayout(inputCompLayout);
}
public void createClassNameControl() {
this.classNameComplex = TextComplex.builder(inputComposite, dataBindingContext,
PojoProperties.value(P_CLASS_NAME).observe(dataModel))
.addValidator(new NotEmptyValidator("Please provide a valid class name for the handler"))
.labelValue("Class Name:")
.defaultValue(dataModel.getClassName())
.textColSpan(2)
.build();
}
public void createInputTypeControl() {
this.inputTypeComplex = ComboComplex.<LambdaBlueprint> builder()
.composite(inputComposite)
.dataBindingContext(dataBindingContext)
.pojoObservableValue(PojoProperties.value(LambdaFunctionDataModel.class, P_INPUT_TYPE).observe(dataModel))
.labelValue("Input Type:")
.items(lambdaBlueprintConfig.getBlueprints().values())
.defaultItemName(dataModel.getInputType())
.comboColSpan(2)
.build();
handlerTypeDescriptionLink = newLink(inputComposite, LambdaConstants.webLinkListener,
dataModel.getSelectedBlueprint().getDescription(), 3);
setItalicFont(handlerTypeDescriptionLink);
}
public void createSeparator() {
Label separator = new Label(group, SWT.HORIZONTAL | SWT.SEPARATOR);
separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
public TextComplex getPackageNameComplex() {
return packageNameComplex;
}
public void createHandlerSourcePreview() {
newFillingLabel(group, "Preview:", 1);
sourcePreviewDocument = new Document("");
IPreferenceStore javaPluginPrefStore = JavaPlugin.getDefault()
.getCombinedPreferenceStore();
sourcePreview = new JavaSourceViewer(group, null, null, false,
SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, javaPluginPrefStore);
sourcePreview.setEditable(false);
sourcePreview.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
// Setting up Java Syntax Highlight
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
tools.setupJavaDocumentPartitioner(sourcePreviewDocument, IJavaPartitions.JAVA_PARTITIONING);
SimpleJavaSourceViewerConfiguration sourceConfig = new SimpleJavaSourceViewerConfiguration(
tools.getColorManager(), javaPluginPrefStore, null,
IJavaPartitions.JAVA_PARTITIONING, true);
sourcePreview.configure(sourceConfig);
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
gridData.horizontalSpan = 1;
gridData.heightHint = 50;
sourcePreview.getTextWidget().setLayoutData(gridData);
sourcePreview.setDocument(sourcePreviewDocument);
dataModel.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
onPropertyChange();
}
});
}
private void onPropertyChange() {
Template template = CodeTemplateManager.getInstance().getLambdaHandlerTemplate(
dataModel.getSelectedBlueprint());
LambdaBlueprintTemplateData freeMarkerDataModel = dataModel.collectLambdaBlueprintTemplateData();
if (template == null || freeMarkerDataModel == null) {
return;
}
handlerTypeDescriptionLink.setText(dataModel.getSelectedBlueprint().getDescription());
String source;
try {
source = CodeTemplateManager.processTemplateWithData(template, freeMarkerDataModel);
} catch (TemplateException | IOException e) {
throw new RuntimeException("Failed to generate handler source preview", e);
}
if (sourcePreviewDocument != null) {
sourcePreviewDocument.set(source);
}
if (sourcePreview != null) {
sourcePreview.getTextWidget().setRedraw(true);
}
}
public void initialize() {
onPropertyChange();
}
private Font italicFont;
private void setItalicFont(Control control) {
FontData[] fontData = control.getFont()
.getFontData();
for (FontData fd : fontData) {
fd.setStyle(SWT.ITALIC);
}
italicFont = new Font(Display.getDefault(), fontData);
control.setFont(italicFont);
}
public void dispose() {
if (italicFont != null) {
italicFont.dispose();
}
}
}
| 7,929 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/util/FunctionProjectUtil.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.project.wizard.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import com.amazonaws.eclipse.core.maven.MavenFactory;
import com.amazonaws.eclipse.core.validator.JavaPackageName;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.blueprint.ServerlessBlueprint;
import com.amazonaws.eclipse.lambda.model.LambdaFunctionDataModel;
import com.amazonaws.eclipse.lambda.project.template.CodeTemplateManager;
import com.amazonaws.eclipse.lambda.project.template.data.LambdaBlueprintTemplateData;
import com.amazonaws.eclipse.lambda.project.template.data.PomFileTemplateData;
import com.amazonaws.eclipse.lambda.project.wizard.model.LambdaFunctionWizardDataModel;
import com.amazonaws.eclipse.lambda.project.wizard.model.NewServerlessProjectDataModel;
import com.amazonaws.eclipse.lambda.serverless.template.ServerlessDataModelTemplateData;
import com.amazonaws.eclipse.lambda.serverless.template.ServerlessHandlerTemplateData;
import com.amazonaws.util.IOUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* Class that manages adding files (Java files, resource files, or configuration files) to project.
*/
public class FunctionProjectUtil {
public static void createLambdaBlueprintProject(IProject project, LambdaFunctionWizardDataModel dataModel)
throws TemplateException, IOException, CoreException {
LambdaFunctionDataModel lambdaFunctionDataModel = dataModel.getLambdaFunctionDataModel();
emitLambdaHandler(project, lambdaFunctionDataModel);
emitLambdaTestUtils(project, lambdaFunctionDataModel);
emitLambdaTestContext(project, lambdaFunctionDataModel);
emitLambdaHandlerTest(project, lambdaFunctionDataModel);
emitLambdaTestJson(project, lambdaFunctionDataModel);
emitLambdaPom(project, dataModel);
}
/**
* TODO consider to add Lambda function to any project, not only to Lambda project.
*/
public static void createLambdaHandler(IProject project, LambdaFunctionDataModel dataModel)
throws TemplateException, IOException, CoreException {
emitLambdaHandler(project, dataModel);
emitLambdaTestUtils(project, dataModel);
emitLambdaTestContext(project, dataModel);
emitLambdaHandlerTest(project, dataModel);
emitLambdaTestJson(project, dataModel);
}
public static File emitLambdaProjectReadme(IProject project, LambdaFunctionDataModel dataModel)
throws TemplateException, IOException, CoreException {
Template readmeTemplate = CodeTemplateManager.getInstance().getlambdaProjectReadmeTemplate();
LambdaBlueprintTemplateData templateData = dataModel.collectLambdaBlueprintTemplateData();
String readmeContent = CodeTemplateManager.processTemplateWithData(readmeTemplate, templateData);
return addFileToProject(project, "README.html", readmeContent);
}
public static void createServerlessBlueprintProject(IProject project, NewServerlessProjectDataModel dataModel)
throws JsonParseException, JsonMappingException, IOException, CoreException, TemplateException {
emitServerlessModels(project, dataModel);
emitServerlessHandlers(project, dataModel);
emitServerlessSam(project, dataModel);
emitServerlessPom(project, dataModel);
}
private static void emitLambdaHandler(IProject project, LambdaFunctionDataModel dataModel)
throws TemplateException, IOException, CoreException {
Template handlerTemplate = CodeTemplateManager.getInstance().getLambdaHandlerTemplate(
dataModel.getSelectedBlueprint());
LambdaBlueprintTemplateData freeMarkerDataModel = dataModel.collectLambdaBlueprintTemplateData();
String handlerContent = CodeTemplateManager.processTemplateWithData(handlerTemplate, freeMarkerDataModel);
addSourceClassToProject(
project,
JavaPackageName.parse(freeMarkerDataModel.getPackageName()),
freeMarkerDataModel.getHandlerClassName(),
handlerContent);
}
private static void emitLambdaTestUtils(IProject project, LambdaFunctionDataModel dataModel)
throws TemplateException, IOException, CoreException {
Template testUtilTemplate = CodeTemplateManager.getInstance().getTestUtilsTemplate();
LambdaBlueprintTemplateData freeMarkerDataModel = dataModel.collectLambdaBlueprintTemplateData();
String testUtilContent = CodeTemplateManager.processTemplateWithData(testUtilTemplate, freeMarkerDataModel);
addTestClassToProject(
project,
JavaPackageName.parse(freeMarkerDataModel.getPackageName()),
"TestUtils",
testUtilContent);
}
private static void emitLambdaTestContext(IProject project, LambdaFunctionDataModel dataModel)
throws TemplateException, IOException, CoreException {
Template testContextTemplate = CodeTemplateManager.getInstance().getTestContextTemplate();
LambdaBlueprintTemplateData freeMarkerDataModel = dataModel.collectLambdaBlueprintTemplateData();
String testContextContent = CodeTemplateManager.processTemplateWithData(testContextTemplate, freeMarkerDataModel);
addTestClassToProject(
project,
JavaPackageName.parse(freeMarkerDataModel.getPackageName()),
"TestContext",
testContextContent);
}
private static void emitLambdaHandlerTest(IProject project, LambdaFunctionDataModel dataModel)
throws TemplateException, IOException, CoreException {
Template handlerTestTemplate = CodeTemplateManager.getInstance().getLambdaHandlerTestTemplate(
dataModel.getSelectedBlueprint());
LambdaBlueprintTemplateData freeMarkerDataModel = dataModel.collectLambdaBlueprintTemplateData();
String handlerTestContent = CodeTemplateManager.processTemplateWithData(handlerTestTemplate, freeMarkerDataModel);
addTestClassToProject(
project,
JavaPackageName.parse(freeMarkerDataModel.getPackageName()),
freeMarkerDataModel.getHandlerTestClassName(),
handlerTestContent);
}
private static void emitLambdaTestJson(IProject project, LambdaFunctionDataModel dataModel)
throws FileNotFoundException, IOException, CoreException {
File testJsonFile = CodeTemplateManager.getInstance().getLambdaTestJsonFile(
dataModel.getSelectedBlueprint());
if (testJsonFile != null) {
addTestResourceToProject(project, testJsonFile.getName(), testJsonFile);
}
}
private static void emitLambdaPom(IProject project, LambdaFunctionWizardDataModel dataModel)
throws CoreException, TemplateException, IOException {
LambdaFunctionDataModel lambdaFunctionDataModel = dataModel.getLambdaFunctionDataModel();
Template pomTemplate = CodeTemplateManager.getInstance().getLambdaBlueprintPomTemplate(
lambdaFunctionDataModel.getSelectedBlueprint());
PomFileTemplateData pomTemplateData = dataModel.collectPomTemplateData();
String pomContent = CodeTemplateManager.processTemplateWithData(pomTemplate, pomTemplateData);
addFileToProject(project, "pom.xml", pomContent);
}
private static void emitServerlessModels(IProject project, NewServerlessProjectDataModel dataModel)
throws TemplateException, IOException, CoreException {
if (dataModel.getSelectedBlueprint().isNeedLambdaProxyIntegrationModel()) {
ServerlessDataModelTemplateData templateData = dataModel.getServerlessDataModelTemplateData();
addSourceClassToProject(
project,
JavaPackageName.parse(templateData.getPackageName()),
templateData.getServerlessInputClassName(),
CodeTemplateManager.processTemplateWithData(
CodeTemplateManager.getInstance().getServerlessInputClassTemplate(),
templateData));
addSourceClassToProject(
project,
JavaPackageName.parse(templateData.getPackageName()),
templateData.getServerlessOutputClassName(),
CodeTemplateManager.processTemplateWithData(
CodeTemplateManager.getInstance().getServerlessOutputClassTemplate(),
templateData));
}
}
private static void emitServerlessHandlers(IProject project, NewServerlessProjectDataModel dataModel)
throws IOException, CoreException, TemplateException {
ServerlessBlueprint blueprint = dataModel.getSelectedBlueprint();
for (ServerlessHandlerTemplateData templateData : dataModel.getServerlessHandlerTemplateData()) {
if (dataModel.isUseBlueprint()) {
addSourceClassToProject(
project,
JavaPackageName.parse(templateData.getPackageName()),
templateData.getClassName(),
CodeTemplateManager.processTemplateWithData(
CodeTemplateManager.getInstance().getServerlessHandlerClassTemplate(blueprint, templateData.getClassName()),
templateData));
} else {
addSourceClassToProject(
project,
JavaPackageName.parse(templateData.getPackageName()),
templateData.getClassName(),
CodeTemplateManager.processTemplateWithData(
CodeTemplateManager.getInstance().getServerlessHandlerClassTemplate(),
templateData));
}
}
}
private static void emitServerlessSam(IProject project, NewServerlessProjectDataModel dataModel)
throws FileNotFoundException, IOException, CoreException, TemplateException {
addFileToProject(project, CodeTemplateManager.SAM_FILE_NAME,
CodeTemplateManager.processTemplateWithData(CodeTemplateManager.getInstance().getServerlessSamTemplate(dataModel.getSelectedBlueprint()),
dataModel.getServerlessSamTemplateData()));
}
private static void emitServerlessPom(IProject project, NewServerlessProjectDataModel dataModel)
throws CoreException, TemplateException, IOException {
addFileToProject(project, "pom.xml",
CodeTemplateManager.processTemplateWithData(
CodeTemplateManager.getInstance().getServerlessPomFile(dataModel.getSelectedBlueprint()),
dataModel.getServerlessPomTemplateData()));
}
public static File emitServerlessReadme(IProject project, NewServerlessProjectDataModel dataModel)
throws FileNotFoundException, IOException, CoreException {
return addFileToProject(
project,
"README.html",
CodeTemplateManager.getInstance().getServerlessReadmeFile());
}
public static File getServerlessTemplateFile(IProject project) {
return getProjectDirectory(project, CodeTemplateManager.SAM_FILE_NAME).toFile();
}
private static void addSourceClassToProject(IProject project,
JavaPackageName packageName, String className, String classContent)
throws CoreException, FileNotFoundException {
IPath srcRoot = getProjectDirectory(project, MavenFactory.getMavenSourceFolder());
String fileName = className + ".java";
addClassToProject(srcRoot, packageName, fileName, classContent);
}
private static void addTestClassToProject(IProject project,
JavaPackageName packageName, String className, String classContent)
throws CoreException, FileNotFoundException {
IPath tstRoot = getProjectDirectory(project, MavenFactory.getMavenTestFolder());
String fileName = className + ".java";
addClassToProject(tstRoot, packageName, fileName, classContent);
}
private static void addTestResourceToProject(IProject project, String fileName, File file)
throws FileNotFoundException, IOException, CoreException {
IPath testResourcePath = getProjectDirectory(project, MavenFactory.getMavenTestResourceFolder());
addFileToProject(testResourcePath, fileName, file);
}
/**
* Add a Java class to project.
*
* @param root - The package root path for the Java class.
* @param packageName - The package name model
* @param fileName - The Java class file name
* @param classContent - The Java class file content.
*/
private static void addClassToProject(IPath root,
JavaPackageName packageName, String fileName, String classContent)
throws CoreException, FileNotFoundException {
IPath targetPath = root;
for (String component : packageName.getComponents()) {
targetPath = targetPath.append(component);
}
addFileToProject(targetPath, fileName, classContent);
}
/*
* Add file to the root of the specified project.
*/
private static File addFileToProject(IProject project, String fileName, File file)
throws FileNotFoundException, IOException, CoreException {
IPath targetPath = getProjectDirectory(project, null);
String fileContent = IOUtils.toString(new FileInputStream(file));
return addFileToProject(targetPath, fileName, fileContent);
}
/*
* Add a file to the root of the specified project.
*/
private static File addFileToProject(IProject project, String fileName, String fileContent)
throws FileNotFoundException, CoreException {
IPath targetPath = getProjectDirectory(project, null);
return addFileToProject(targetPath, fileName, fileContent);
}
private static File addFileToProject(IPath targetPath, String fileName, File file)
throws FileNotFoundException, IOException, CoreException {
String fileContent = IOUtils.toString(new FileInputStream(file));
return addFileToProject(targetPath, fileName, fileContent);
}
/**
* Add a file with the specified content to the target path.
*
* @param targetPath - The target location for the file to be added in.
* @param fileName - The file name
* @param fileContent - The file content
* @return The file in the target location.
*/
private static File addFileToProject(IPath targetPath, String fileName, String fileContent)
throws CoreException, FileNotFoundException {
IFileStore targetFileStore = EFS.getLocalFileSystem().fromLocalFile(
targetPath.append(fileName).toFile());
File targetFile = targetFileStore.toLocalFile(EFS.NONE, null);
targetFile.getParentFile().mkdirs();
try (PrintStream ps = new PrintStream(new FileOutputStream(targetFile))) {
ps.print(fileContent);
}
return targetFile;
}
/*
* Return the absolute path of the specified location relative to the project.
*/
public static IPath getProjectDirectory(IProject project, String path) {
IPath projectRoot = project.getLocation();
if (path == null) {
return projectRoot;
} else {
return projectRoot.append(path);
}
}
public static void refreshProject(IProject project) {
// Finally, refresh the project so that the new files show up
try {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e) {
LambdaPlugin.getDefault().logWarning(
"Failed to refresh project " + project.getName(), e);
}
}
}
| 7,930 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/util/BrowserUtil.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.lambda.project.wizard.util;
import java.net.URL;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
public class BrowserUtil {
private static final int EDITOR_BROWSER_STYLE = IWorkbenchBrowserSupport.AS_EDITOR;
public static void openInternalBrowserAsEditor(URL url) throws PartInitException {
IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport();
browserSupport.createBrowser(EDITOR_BROWSER_STYLE, null, null, null)
.openURL(url);
}
}
| 7,931 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/model/NewServerlessProjectDataModel.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.project.wizard.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.amazonaws.eclipse.core.maven.MavenFactory;
import com.amazonaws.eclipse.core.model.ImportFileDataModel;
import com.amazonaws.eclipse.core.model.MavenConfigurationDataModel;
import com.amazonaws.eclipse.core.model.ProjectNameDataModel;
import com.amazonaws.eclipse.lambda.blueprint.BlueprintsProvider;
import com.amazonaws.eclipse.lambda.blueprint.ServerlessBlueprint;
import com.amazonaws.eclipse.lambda.blueprint.ServerlessBlueprintsConfig;
import com.amazonaws.eclipse.lambda.project.template.CodeTemplateManager;
import com.amazonaws.eclipse.lambda.project.template.data.PomFileTemplateData;
import com.amazonaws.eclipse.lambda.project.template.data.SamFileTemplateData;
import com.amazonaws.eclipse.lambda.serverless.NameUtils;
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.serverless.template.ServerlessDataModelTemplateData;
import com.amazonaws.eclipse.lambda.serverless.template.ServerlessHandlerTemplateData;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import freemarker.template.TemplateException;
/**
* Serverless project creation data model. It also manages all other models throughout this stage, such as
* ServerlessModel, freemarker template models.
*/
public class NewServerlessProjectDataModel {
/* These constants must be the same to the Pojo property names */
public static final String P_BLUEPRINT_NAME = "blueprintName";
public static final String P_USE_BLUEPRINT = "useBlueprint";
public static final String P_USE_SERVERLESS_TEMPLATE_FILE = "useServerlessTemplateFile";
private static final ServerlessBlueprintsConfig BLUEPRINTS_CONFIG = BlueprintsProvider.provideServerlessBlueprints();
/* Function handler section */
private final ProjectNameDataModel projectNameDataModel = new ProjectNameDataModel();
private final MavenConfigurationDataModel mavenConfigurationDataModel = new MavenConfigurationDataModel();
private final ImportFileDataModel importFileDataModel = new ImportFileDataModel();
private ServerlessBlueprint selectedBlueprint = BLUEPRINTS_CONFIG.getBlueprints()
.get(BLUEPRINTS_CONFIG.getDefaultBlueprint());
private String blueprintName = selectedBlueprint.getDisplayName();
private boolean useBlueprint = true;
private boolean useServerlessTemplateFile = false;
private ServerlessModel serverlessModel;
public ProjectNameDataModel getProjectNameDataModel() {
return projectNameDataModel;
}
public MavenConfigurationDataModel getMavenConfigurationDataModel() {
return mavenConfigurationDataModel;
}
public ImportFileDataModel getImportFileDataModel() {
return importFileDataModel;
}
public String getBlueprintName() {
return blueprintName;
}
public void setBlueprintName(String blueprintName) {
this.blueprintName = blueprintName;
this.selectedBlueprint = getServerlessBlueprint(blueprintName);
}
public ServerlessBlueprint getSelectedBlueprint() {
return selectedBlueprint;
}
public boolean isUseBlueprint() {
return useBlueprint;
}
public void setUseBlueprint(boolean useBlueprint) {
this.useBlueprint = useBlueprint;
}
public boolean isUseServerlessTemplateFile() {
return useServerlessTemplateFile;
}
public void setUseServerlessTemplateFile(boolean useServerlessTemplateFile) {
this.useServerlessTemplateFile = useServerlessTemplateFile;
}
public ServerlessDataModelTemplateData getServerlessDataModelTemplateData()
throws JsonParseException, JsonMappingException, IOException, TemplateException {
buildServerlessModel();
ServerlessDataModelTemplateData data = new ServerlessDataModelTemplateData();
data.setPackageName(NameUtils.toModelPackageName(mavenConfigurationDataModel.getPackageName()));
data.setServerlessInputClassName(NameUtils.SERVERLESS_INPUT_CLASS_NAME);
data.setServerlessOutputClassName(NameUtils.SERVERLESS_OUTPUT_CLASS_NAME);
return data;
}
public List<ServerlessHandlerTemplateData> getServerlessHandlerTemplateData()
throws JsonParseException, JsonMappingException, IOException, TemplateException {
buildServerlessModel();
List<ServerlessHandlerTemplateData> handlers = new ArrayList<>();
for (ServerlessFunction function : serverlessModel.getServerlessFunctions().values()) {
ServerlessHandlerTemplateData template = new ServerlessHandlerTemplateData();
String handlerName = function.getHandler();
int lastDotIndex = handlerName.lastIndexOf(".");
if (lastDotIndex < 0) {
template.setPackageName(NameUtils.toHandlerPackageName(mavenConfigurationDataModel.getPackageName()));
} else {
template.setPackageName(handlerName.substring(0, lastDotIndex));
}
template.setClassName(NameUtils.toHandlerClassName(handlerName));
template.setInputFqcn(NameUtils.toServerlessInputModelFqcn(mavenConfigurationDataModel.getPackageName()));
template.setOutputFqcn(NameUtils.toServerlessOutputModelFqcn(mavenConfigurationDataModel.getPackageName()));
handlers.add(template);
}
return handlers;
}
public PomFileTemplateData getServerlessPomTemplateData() {
PomFileTemplateData data = new PomFileTemplateData();
data.setGroupId(mavenConfigurationDataModel.getGroupId());
data.setArtifactId(mavenConfigurationDataModel.getArtifactId());
data.setVersion(mavenConfigurationDataModel.getVersion());
data.setAwsJavaSdkVersion(MavenFactory.getLatestJavaSdkVersion());
return data;
}
public SamFileTemplateData getServerlessSamTemplateData() {
SamFileTemplateData data = new SamFileTemplateData();
data.setPackageName(NameUtils.toHandlerPackageName(mavenConfigurationDataModel.getPackageName()));
data.setArtifactId(mavenConfigurationDataModel.getArtifactId());
data.setVersion(mavenConfigurationDataModel.getVersion());
return data;
}
private void buildServerlessModel() throws JsonParseException, JsonMappingException, IOException, TemplateException {
if (serverlessModel != null) return;
if (isUseBlueprint()) {
ServerlessBlueprint blueprint = getSelectedBlueprint();
String content = CodeTemplateManager.processTemplateWithData(
CodeTemplateManager.getInstance().getServerlessSamTemplate(blueprint), getServerlessSamTemplateData());
serverlessModel = Serverless.loadFromContent(content);
} else {
serverlessModel = Serverless.load(importFileDataModel.getFilePath());
}
}
/**
* Return the ServerlessBlueprint by display name.
*/
private static ServerlessBlueprint getServerlessBlueprint(String displayName) {
for (ServerlessBlueprint blueprint : BLUEPRINTS_CONFIG.getBlueprints().values()) {
if (blueprint.getDisplayName().equals(displayName)) {
return blueprint;
}
}
return null;
}
}
| 7,932 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/model/DeployServerlessProjectDataModel.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.project.wizard.model;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import com.amazonaws.eclipse.cloudformation.model.ParametersDataModel;
import com.amazonaws.eclipse.core.model.MultipleSelectionListDataModel;
import com.amazonaws.eclipse.core.model.RegionDataModel;
import com.amazonaws.eclipse.core.model.SelectOrCreateBucketDataModel;
import com.amazonaws.eclipse.lambda.model.SelectOrInputStackDataModel;
import com.amazonaws.eclipse.lambda.project.metadata.ServerlessProjectMetadata;
import com.amazonaws.services.cloudformation.model.Capability;
public class DeployServerlessProjectDataModel {
private final RegionDataModel regionDataModel = new RegionDataModel();
private final SelectOrCreateBucketDataModel bucketDataModel = new SelectOrCreateBucketDataModel();
private final SelectOrInputStackDataModel stackDataModel = new SelectOrInputStackDataModel();
private final ParametersDataModel parametersDataModel = new ParametersDataModel();
private final MultipleSelectionListDataModel<Capability> capabilitiesDataModel = new MultipleSelectionListDataModel<>();
private final IProject project;
private final String projectName;
private final Set<String> handlerClasses;
private ServerlessProjectMetadata metadata = new ServerlessProjectMetadata();
private String lambdaFunctionJarFileKeyName;
private File updatedServerlessTemplate;
public DeployServerlessProjectDataModel(IProject project, Set<String> handlerClasses) {
this.project = project;
this.projectName = project.getName();
this.stackDataModel.setDefaultStackNamePrefix(projectName);
this.handlerClasses = handlerClasses;
}
// Add listeners for property changing.
public void addPropertyChangeListener(PropertyChangeListener listener) {
bucketDataModel.addPropertyChangeListener(listener);
stackDataModel.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
bucketDataModel.removePropertyChangeListener(listener);
bucketDataModel.removePropertyChangeListener(listener);
}
public RegionDataModel getRegionDataModel() {
return this.regionDataModel;
}
public SelectOrCreateBucketDataModel getBucketDataModel() {
return bucketDataModel;
}
public SelectOrInputStackDataModel getStackDataModel() {
return stackDataModel;
}
public MultipleSelectionListDataModel<Capability> getCapabilitiesDataModel() {
return capabilitiesDataModel;
}
public ParametersDataModel getParametersDataModel() {
return parametersDataModel;
}
public IProject getProject() {
return project;
}
public String getProjectName() {
return projectName;
}
public String getLambdaFunctionJarFileKeyName() {
return lambdaFunctionJarFileKeyName;
}
public void setLambdaFunctionJarFileKeyName(String lambdaFunctionJarFileKeyName) {
this.lambdaFunctionJarFileKeyName = lambdaFunctionJarFileKeyName;
}
public File getUpdatedServerlessTemplate() {
return updatedServerlessTemplate;
}
public void setUpdatedServerlessTemplate(File updatedServerlessTemplate) {
this.updatedServerlessTemplate = updatedServerlessTemplate;
}
public Set<String> getHandlerClasses() {
return handlerClasses;
}
public void setMetadata(ServerlessProjectMetadata metadata) {
this.metadata = metadata == null ? new ServerlessProjectMetadata() : metadata;
}
/**
* The returned metadata is nonnull
*/
public ServerlessProjectMetadata getMetadata() {
if (metadata == null) {
metadata = new ServerlessProjectMetadata();
}
return metadata;
}
}
| 7,933 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/model/LambdaFunctionWizardDataModel.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.project.wizard.model;
import com.amazonaws.eclipse.core.maven.MavenFactory;
import com.amazonaws.eclipse.core.model.MavenConfigurationDataModel;
import com.amazonaws.eclipse.core.model.ProjectNameDataModel;
import com.amazonaws.eclipse.lambda.model.LambdaFunctionDataModel;
import com.amazonaws.eclipse.lambda.project.template.data.PomFileTemplateData;
/**
* This data model is shared by both New AWS Lambda Java Project wizard and New AWS Lambda Function wizard.
*/
public class LambdaFunctionWizardDataModel {
public static final String P_SHOW_README_FILE = "showReadmeFile";
private final ProjectNameDataModel projectNameDataModel = new ProjectNameDataModel();
private final MavenConfigurationDataModel mavenConfigurationDataModel = new MavenConfigurationDataModel();
private final LambdaFunctionDataModel lambdaFunctionDataModel = new LambdaFunctionDataModel();
/* Show README checkbox */
private boolean showReadmeFile = true;
public ProjectNameDataModel getProjectNameDataModel() {
return projectNameDataModel;
}
public MavenConfigurationDataModel getMavenConfigurationDataModel() {
return mavenConfigurationDataModel;
}
public LambdaFunctionDataModel getLambdaFunctionDataModel() {
return lambdaFunctionDataModel;
}
public boolean isShowReadmeFile() {
return showReadmeFile;
}
public void setShowReadmeFile(boolean showReadmeFile) {
this.showReadmeFile = showReadmeFile;
}
public PomFileTemplateData collectPomTemplateData() {
PomFileTemplateData pomData = new PomFileTemplateData();
pomData.setGroupId(mavenConfigurationDataModel.getGroupId());
pomData.setArtifactId(mavenConfigurationDataModel.getArtifactId());
pomData.setVersion(mavenConfigurationDataModel.getVersion());
pomData.setAwsJavaSdkVersion(MavenFactory.getLatestJavaSdkVersion());
return pomData;
}
}
| 7,934 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/wizard/model/RunSamLocalDataModel.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.project.wizard.model;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_EVENT;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_HOST;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_LAMBDA_IDENTIFIER;
import static com.amazonaws.eclipse.lambda.launching.SamLocalConstants.A_PORT;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.model.ImportFileDataModel;
import com.amazonaws.eclipse.core.model.RegionDataModel;
/**
* Data model for debugging Sam function using SAM Local.
*/
public class RunSamLocalDataModel {
public static final int DEFAULT_DEBUG_PORT = 5858;
public static final String DEFAULT_MAVEN_GOALS = "clean package";
public static final String DEFAULT_PROFILE = "default";
public static final String DEFAULT_REGION = "us-east-1";
public static final int DEFAULT_TIME_OUT = 300;
public static final String P_DEBUG_PORT = "debugPort";
public static final String P_SAM_ACTION = "samAction";
public static final String P_SAM_RUNTIME = "samRuntime";
public static final String P_MAVEN_GOALS = "mavenGoals";
public static final String P_CODE_URI = "codeUri";
public static final String P_TIME_OUT = "timeOut";
private final RegionDataModel regionDataModel = new RegionDataModel();
private final ImportFileDataModel workspaceDataModel = new ImportFileDataModel();
private final ImportFileDataModel templateFileLocationDataModel = new ImportFileDataModel();
private final ImportFileDataModel envvarFileLocationDataModel = new ImportFileDataModel();
private AccountInfo account;
private String mavenGoals = DEFAULT_MAVEN_GOALS;
private String samRuntime;
private int debugPort = DEFAULT_DEBUG_PORT;
private SamAction samAction = SamAction.INVOKE;
private AttributeMapConvertible actionDataModel;
private String codeUri;
private int timeOut = DEFAULT_TIME_OUT;
public String getMavenGoals() {
return mavenGoals;
}
public void setMavenGoals(String mavenGoals) {
this.mavenGoals = mavenGoals;
}
public String getSamRuntime() {
return samRuntime;
}
public void setSamRuntime(String samRuntime) {
this.samRuntime = samRuntime;
}
public String getCodeUri() {
return codeUri;
}
public void setCodeUri(String codeUri) {
this.codeUri = codeUri;
}
public int getTimeOut() {
return timeOut;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
public enum SamAction {
INVOKE("invoke", "Lambda Function"),
START_API("start-api", "API Gateway"),
;
// Action name must be a valid command line action `sam local ${action}`
private final String name;
private final String description;
private SamAction(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public static List<SamAction> toList() {
return Arrays.asList(SamAction.values());
}
public static SamAction fromValue(String value) {
for (SamAction samAction : SamAction.values()) {
if (samAction.getName().equals(value)) {
return samAction;
}
}
return null;
}
}
public AccountInfo getAccount() {
return account;
}
public void setAccount(AccountInfo account) {
this.account = account;
}
public RegionDataModel getRegionDataModel() {
return regionDataModel;
}
public ImportFileDataModel getWorkspaceDataModel() {
return workspaceDataModel;
}
public ImportFileDataModel getTemplateFileLocationDataModel() {
return templateFileLocationDataModel;
}
public ImportFileDataModel getEnvvarFileLocationDataModel() {
return envvarFileLocationDataModel;
}
public int getDebugPort() {
return debugPort;
}
public void setDebugPort(int debugPort) {
this.debugPort = debugPort;
}
public AttributeMapConvertible getActionDataModel() {
return actionDataModel;
}
public void setActionDataModel(AttributeMapConvertible actionDataModel) {
this.actionDataModel = actionDataModel;
}
public SamAction getSamAction() {
return samAction;
}
public void setSamAction(SamAction samAction) {
this.samAction = samAction;
}
public static class SamLocalInvokeFunctionDataModel implements AttributeMapConvertible {
public static final String P_LAMBDA_IDENTIFIER = "lambdaIdentifier";
private String lambdaIdentifier;
private final ImportFileDataModel eventFileLocationDataModel = new ImportFileDataModel();
public String getLambdaIdentifier() {
return lambdaIdentifier;
}
public void setLambdaIdentifier(String lambdaIdentifier) {
this.lambdaIdentifier = lambdaIdentifier;
}
public ImportFileDataModel getEventFileLocationDataModel() {
return eventFileLocationDataModel;
}
@Override
public Map<String, String> toAttributeMap() {
Map<String, String> attributes = new HashMap<>();
attributes.put(A_EVENT, eventFileLocationDataModel.getFilePath());
attributes.put(A_LAMBDA_IDENTIFIER, lambdaIdentifier);
return attributes;
}
}
public static class SamLocalStartApiDataModel implements AttributeMapConvertible {
public static final int DEFAULT_PORT = 3000;
public static final String DEFAULT_HOST = "127.0.0.1";
public static final String P_PORT = "port";
public static final String P_HOST = "host";
private String host = DEFAULT_HOST;
private int port = DEFAULT_PORT;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Override
public Map<String, String> toAttributeMap() {
Map<String, String> attributes = new HashMap<>();
attributes.put(A_HOST, host);
attributes.put(A_PORT, String.valueOf(port));
return attributes;
}
}
public static interface AttributeMapConvertible {
Map<String, String> toAttributeMap();
}
}
| 7,935 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/template/CodeTemplateManager.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.project.template;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.eclipse.core.runtime.FileLocator;
import org.osgi.framework.Bundle;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.blueprint.LambdaBlueprint;
import com.amazonaws.eclipse.lambda.blueprint.ServerlessBlueprint;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
/**
* Class that manages Freemarker code template and Json configuration files.
* Use a get*Template method to get a certain Freemarker template.
* Use a get*File method to get a certain File.
*/
public class CodeTemplateManager {
private static final String CODE_TEMPLATE_BASE_DIR = "code-template";
private static final String LAMBDA_BLUEPRINTS_BASE_DIR = "lambda";
private static final String SERVERLESS_BLUEPRINTS_BASE_DIR = "serverless";
private static final String LAMBDA_BLUEPRINTS_CONFIG_PATH = String.format("%s/%s", LAMBDA_BLUEPRINTS_BASE_DIR, "blueprints.json");
private static final String SERVERLESS_BLUEPRINTS_CONFIG_PATH = String.format("%s/%s", SERVERLESS_BLUEPRINTS_BASE_DIR, "blueprints.json");
private static final String LAMBDA_BLUEPRINT_HANDLER_NAME = "handler.java.ftl";
private static final String LAMBDA_BLUEPRINT_HANDLER_TEST_NAME = "handler-test.java.ftl";
private static final String LAMBDA_BLUEPRINT_POM_NAME = "pom.xml.ftl";
private static final String LAMBDA_README_FILE_PATH = String.format("%s/%s", LAMBDA_BLUEPRINTS_BASE_DIR, "README.ftl");
private static final String SERVERLESS_README_FILE_PATH = String.format("%s/%s", SERVERLESS_BLUEPRINTS_BASE_DIR, "README.html");
private static final String SERVERLESS_INPUT_MODEL_PATH = String.format("%s/%s", SERVERLESS_BLUEPRINTS_BASE_DIR, "serverless-input.ftl");
private static final String SERVERLESS_OUTPUT_MODEL_PATH = String.format("%s/%s", SERVERLESS_BLUEPRINTS_BASE_DIR, "serverless-output.ftl");
private static final String SERVERLESS_HANDLER_CLASS_PATH = String.format("%s/%s", SERVERLESS_BLUEPRINTS_BASE_DIR, "serverless-handler.ftl");
public static final String SAM_FILE_NAME = "serverless.template";
public static final String SERVERLESS_BLUEPRINT_SAM_NAME = "serverless.template.ftl";
private static final String SERVERLESS_BLUEPRINT_POM_NAME = "pom.xml.ftl";
private static final String TEST_RESOURCES_BASE_DIR = "test-resource";
private static final String TEST_CLASSES_BASE_DIR = "test-class";
private static final String TEST_CONTEXT_FILE_PATH = String.format("%s/%s", TEST_CLASSES_BASE_DIR, "test-context.ftl");
private static final String TEST_UTILS_FILE_PATH = String.format("%s/%s", TEST_CLASSES_BASE_DIR, "test-utils.ftl");
private final Configuration freemarkerCfg;
private static final CodeTemplateManager INSTANCE = new CodeTemplateManager();
private CodeTemplateManager() {
freemarkerCfg = setupFreemarker();
}
public static CodeTemplateManager getInstance() {
return INSTANCE;
}
/**
* Helper method to return the populated content rendered by Freemarker to the given
* template and template data.
*/
public static String processTemplateWithData(Template template, Object templateData)
throws TemplateException, IOException {
try (StringWriter stringWriter = new StringWriter()) {
template.process(templateData, stringWriter);
stringWriter.flush();
return stringWriter.toString();
}
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.project.template.data.LambdaBlueprintTemplateData}
*/
public Template getLambdaHandlerTemplate(LambdaBlueprint blueprint) {
return blueprint == null ? null : getTemplate(String.format("%s/%s/%s",
LAMBDA_BLUEPRINTS_BASE_DIR, blueprint.getBaseDir(), LAMBDA_BLUEPRINT_HANDLER_NAME));
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.project.template.data.LambdaBlueprintTemplateData}
*/
public Template getLambdaHandlerTestTemplate(LambdaBlueprint blueprint) {
return blueprint == null ? null : getTemplate(String.format("%s/%s/%s",
LAMBDA_BLUEPRINTS_BASE_DIR, blueprint.getBaseDir(), LAMBDA_BLUEPRINT_HANDLER_TEST_NAME));
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.project.template.data.PomFileTemplateData}
*/
public Template getLambdaBlueprintPomTemplate(LambdaBlueprint blueprint) {
return blueprint == null ? null : getTemplate(String.format("%s/%s/%s",
LAMBDA_BLUEPRINTS_BASE_DIR, blueprint.getBaseDir(), LAMBDA_BLUEPRINT_POM_NAME));
}
// Test JSON file could be null for some blueprints
public File getLambdaTestJsonFile(LambdaBlueprint blueprint) {
return blueprint == null || blueprint.getTestJsonFile() == null ? null :
getFile(String.format("%s/%s", TEST_RESOURCES_BASE_DIR, blueprint.getTestJsonFile()));
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.project.template.data.LambdaBlueprintTemplateData}
*/
public Template getTestContextTemplate() {
return getTemplate(TEST_CONTEXT_FILE_PATH);
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.project.template.data.LambdaBlueprintTemplateData}
*/
public Template getTestUtilsTemplate() {
return getTemplate(TEST_UTILS_FILE_PATH);
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.project.template.data.LambdaBlueprintTemplateData}
*/
public Template getlambdaProjectReadmeTemplate() {
return getTemplate(LAMBDA_README_FILE_PATH);
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.serverless.template.ServerlessDataModelTemplateData}
*/
public Template getServerlessInputClassTemplate() {
return getTemplate(SERVERLESS_INPUT_MODEL_PATH);
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.serverless.template.ServerlessDataModelTemplateData}
*/
public Template getServerlessOutputClassTemplate() {
return getTemplate(SERVERLESS_OUTPUT_MODEL_PATH);
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.serverless.template.ServerlessHandlerTemplateData}
*/
public Template getServerlessHandlerClassTemplate() {
return getTemplate(SERVERLESS_HANDLER_CLASS_PATH);
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.serverless.template.ServerlessHandlerTemplateData}
*/
public Template getServerlessHandlerClassTemplate(ServerlessBlueprint blueprint, String handlerName) {
String templatePath = blueprint.getHandlerTemplatePaths().get(handlerName);
return getTemplate(String.format("%s/%s/%s", SERVERLESS_BLUEPRINTS_BASE_DIR, blueprint.getBaseDir(), templatePath));
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.project.template.data.SamFileTemplateData}
*/
public Template getServerlessSamTemplate(ServerlessBlueprint blueprint) {
return getTemplate(String.format("%s/%s/%s", SERVERLESS_BLUEPRINTS_BASE_DIR, blueprint.getBaseDir(),
SERVERLESS_BLUEPRINT_SAM_NAME));
}
/**
* Template data model {@link #com.amazonaws.eclipse.lambda.project.template.data.PomFileTemplateData}
*/
public Template getServerlessPomFile(ServerlessBlueprint blueprint) {
return getTemplate(String.format("%s/%s/%s", SERVERLESS_BLUEPRINTS_BASE_DIR, blueprint.getBaseDir(), SERVERLESS_BLUEPRINT_POM_NAME));
}
public File getServerlessBlueprintsConfigFile() {
return getFile(SERVERLESS_BLUEPRINTS_CONFIG_PATH);
}
public File getLambdaBlueprintsConfigFile() {
return getFile(LAMBDA_BLUEPRINTS_CONFIG_PATH);
}
public File getServerlessReadmeFile() {
return getFile(SERVERLESS_README_FILE_PATH);
}
private Configuration setupFreemarker() {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_21);
try {
cfg.setDirectoryForTemplateLoading(getCodeTemplateBasedir());
} catch (IOException e) {
throw new RuntimeException(
"Failed to setup freemarker template directory.", e);
}
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
return cfg;
}
private File getCodeTemplateBasedir() {
Bundle bundle = LambdaPlugin.getDefault().getBundle();
File file = null;
try {
URL bundleBaseUrl = FileLocator.toFileURL(bundle.getEntry(CODE_TEMPLATE_BASE_DIR));
URI bundleBaseUri = new URI(bundleBaseUrl.getProtocol(), bundleBaseUrl.getPath(), null);
file = new File(bundleBaseUri);
} catch (IOException e) {
throw new RuntimeException("Failed to find plugin bundle root.", e);
} catch (URISyntaxException e) {
throw new RuntimeException("Failed to find plugin bundle root.", e);
}
return file;
}
private File getFile(String path) {
return new File(getCodeTemplateBasedir(), path);
}
private Template getTemplate(String templatePath) {
try {
return freemarkerCfg.getTemplate(templatePath);
} catch (IOException e) {
throw new RuntimeException(
"Failed to load Freemarker template from " + templatePath, e);
}
}
}
| 7,936 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/template | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/template/data/LambdaBlueprintTemplateData.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.project.template.data;
//TODO make it immutable
/*
* Data model of Freemarker template for handler.java, handler-test.java, test-utils.java, and test-context.java
*/
public class LambdaBlueprintTemplateData {
private String packageName;
private String handlerClassName;
private String handlerTestClassName;
private String inputJsonFileName;
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getHandlerClassName() {
return handlerClassName;
}
public void setHandlerClassName(String handlerClassName) {
this.handlerClassName = handlerClassName;
}
public String getHandlerTestClassName() {
return handlerTestClassName;
}
public void setHandlerTestClassName(String handlerTestClassName) {
this.handlerTestClassName = handlerTestClassName;
}
public String getInputJsonFileName() {
return inputJsonFileName;
}
public void setInputJsonFileName(String inputJsonFileName) {
this.inputJsonFileName = inputJsonFileName;
}
}
| 7,937 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/template | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/template/data/SamFileTemplateData.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.project.template.data;
/**
* Data model of Freemarker for serverless.template file.
*/
public class SamFileTemplateData {
private String packageName;
private String artifactId;
private String version;
public String getArtifactId() {
return artifactId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
} | 7,938 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/template | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/template/data/PomFileTemplateData.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.project.template.data;
/**
* Data model of Freemarker template for pom.xml
*/
public class PomFileTemplateData {
private String groupId;
private String artifactId;
private String version;
private String awsJavaSdkVersion;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getArtifactId() {
return artifactId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getAwsJavaSdkVersion() {
return awsJavaSdkVersion;
}
public void setAwsJavaSdkVersion(String awsJavaSdkVersion) {
this.awsJavaSdkVersion = awsJavaSdkVersion;
}
}
| 7,939 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/metadata/ServerlessProjectMetadata.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.project.metadata;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* Metadata POJO for deploying Serverless project. This POJO records the last deployment information
* for the corresponding Serverless project which could be reused for the next time of deployment.
*/
public class ServerlessProjectMetadata {
// Lambda handler package prefix
private String packagePrefix;
// Region ID for last deployment
private String lastDeploymentRegionId;
// Configurations for last deployment to a specific region
private Map<String, RegionConfig> regionConfig;
public String getLastDeploymentRegionId() {
return lastDeploymentRegionId;
}
public void setLastDeploymentRegionId(String lastDeploymentRegionId) {
this.lastDeploymentRegionId = lastDeploymentRegionId;
}
public Map<String, RegionConfig> getRegionConfig() {
return regionConfig;
}
public void setRegionConfig(Map<String, RegionConfig> regionConfig) {
this.regionConfig = regionConfig;
}
public String getPackagePrefix() {
return packagePrefix;
}
public void setPackagePrefix(String packagePrefix) {
this.packagePrefix = packagePrefix;
}
@JsonIgnore
public String getLastDeploymentBucket() {
RegionConfig regionConfig = getDefaultRegionConfig();
return regionConfig == null ? null : regionConfig.getBucket();
}
@JsonIgnore
public String getLastDeploymentBucket(String regionId) {
RegionConfig regionConfig = getRegionConfig(regionId);
return regionConfig == null ? null : regionConfig.getBucket();
}
@JsonIgnore
public void setLastDeploymentBucket(String bucketName) {
RegionConfig regionConfig = getDefaultRegionConfig();
if (regionConfig != null) {
regionConfig.setBucket(bucketName);
}
}
@JsonIgnore
public String getLastDeploymentStack() {
RegionConfig regionConfig = getDefaultRegionConfig();
return regionConfig == null ? null : regionConfig.getStack();
}
@JsonIgnore
public String getLastDeploymentStack(String regionId) {
RegionConfig regionConfig = getRegionConfig(regionId);
return regionConfig == null ? null : regionConfig.getStack();
}
@JsonIgnore
public void setLastDeploymentStack(String stackName) {
RegionConfig regionConfig = getDefaultRegionConfig();
if (regionConfig != null) {
regionConfig.setStack(stackName);
}
}
/**
* Create the path to the last deployment {@link RegionConfig} if it is null and return it.
*/
@JsonIgnore
private RegionConfig getDefaultRegionConfig() {
if (regionConfig == null) {
regionConfig = new HashMap<>();
}
if (lastDeploymentRegionId != null) {
RegionConfig defaultRegionConfig = regionConfig.get(lastDeploymentRegionId);
if (defaultRegionConfig == null) {
defaultRegionConfig = new RegionConfig();
regionConfig.put(lastDeploymentRegionId, defaultRegionConfig);
}
return defaultRegionConfig;
}
return null;
}
@JsonIgnore
private RegionConfig getRegionConfig(String regionId) {
if (regionConfig == null) {
regionConfig = new HashMap<>();
}
return regionId == null ? null : regionConfig.get(regionId);
}
public static class RegionConfig {
private String bucket;
private String stack;
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getStack() {
return stack;
}
public void setStack(String stack) {
this.stack = stack;
}
}
}
| 7,940 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/metadata/ProjectMetadataManager.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.project.metadata;
import static com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil.getProjectDirectory;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
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.ObjectMapper;
/**
* Class that manages loading and saving Serverless and Lambda projects metadata caches.
* These cached data are saved as hidden files in the target project root.
*/
public class ProjectMetadataManager {
private static final String PROJECT_SETTING_FOLDER_NAME = ".settings";
private static final String LAMBDA_PROJECT_METADATA_FILE = "com.amazonaws.eclipse.lambda.project.json";
private static final String SERVERLESS_PROJECT_METADATA_FILE = "com.amazonaws.eclipse.serverless.project.json";
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
/**
* This function overrides all the existing metadata for the Lambda project.
*/
public static void saveLambdaProjectMetadata(IProject project, LambdaFunctionProjectMetadata metadata)
throws JsonGenerationException, JsonMappingException, IOException {
File metadataFile = getMetadataFile(project, LAMBDA_PROJECT_METADATA_FILE);
MAPPER.writeValue(metadataFile, metadata);
}
public static LambdaFunctionProjectMetadata loadLambdaProjectMetadata(IProject project)
throws JsonParseException, JsonMappingException, IOException {
File metadataFile = getMetadataFile(project, LAMBDA_PROJECT_METADATA_FILE);
if (!metadataFile.exists()) {
return null;
}
return MAPPER.readValue(metadataFile, LambdaFunctionProjectMetadata.class);
}
/**
* This function overrides all the existing metadata for the Serverless project.
*/
public static void saveServerlessProjectMetadata(IProject project, ServerlessProjectMetadata metadata)
throws JsonGenerationException, JsonMappingException, IOException {
File metadataFile = getMetadataFile(project, SERVERLESS_PROJECT_METADATA_FILE);
MAPPER.writeValue(metadataFile, metadata);
}
/**
* Return the cached metadata under the Serverless project. Return null if the file is not found.
*/
public static ServerlessProjectMetadata loadServerlessProjectMetadata(IProject project)
throws JsonParseException, JsonMappingException, IOException {
File metadataFile = getMetadataFile(project, SERVERLESS_PROJECT_METADATA_FILE);
if (!metadataFile.exists()) {
return null;
}
return MAPPER.readValue(metadataFile, ServerlessProjectMetadata.class);
}
private static File getMetadataFile(IProject project, String metadataFileName) {
IPath settingsDir = getProjectDirectory(project, PROJECT_SETTING_FOLDER_NAME);
settingsDir.toFile().mkdirs();
return settingsDir.append(metadataFileName).toFile();
}
}
| 7,941 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/project/metadata/LambdaFunctionProjectMetadata.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.project.metadata;
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* Metadata POJO for deploying or invoking Lambda functions. This POJO records the last Lambda function deployment or invoke
* information which could be reused for the next time of deployment or invoke.
*/
public class LambdaFunctionProjectMetadata {
private String lastDeploymentHandler;
private String lastInvokeHandler;
private final Map<String, LambdaFunctionMetadata> handlerMetadata = new HashMap<>();
/**
* Helper methods for getting and setting last deployment metadata according to {@link #lastDeploymentHandler} field.
*/
/**
* Whether the chosen Lambda handler is deployed yet or not.
*/
public boolean isLastInvokedHandlerDeployed() {
LambdaFunctionMetadata metadata = handlerMetadata.get(lastInvokeHandler);
return metadata == null ? false : metadata.getDeployment() != null;
}
@JsonIgnore
public Region getLastDeploymentRegion() {
LambdaFunctionDeploymentMetadata lastDeploy = getLastDeployment();
return lastDeploy == null ? null : RegionUtils.getRegion(lastDeploy.getRegionId());
}
public void setLastDeploymentRegion(String regionId) {
LambdaFunctionDeploymentMetadata lastDeploy = getLastDeployment();
if (lastDeploy != null) {
lastDeploy.setRegionId(regionId);
}
}
@JsonIgnore
public String getLastDeploymentFunctionName() {
LambdaFunctionDeploymentMetadata lastDeploy = getLastDeployment();
return lastDeploy == null ? null : lastDeploy.getAwsLambdaFunctionName();
}
public void setLastDeploymentFunctionName(String functionName) {
LambdaFunctionDeploymentMetadata lastDeploy = getLastDeployment();
if (lastDeploy != null) {
lastDeploy.setAwsLambdaFunctionName(functionName);
}
}
@JsonIgnore
public String getLastDeploymentBucketName() {
LambdaFunctionDeploymentMetadata lastDeploy = getLastDeployment();
return lastDeploy == null ? null : lastDeploy.getAwsS3BucketName();
}
public void setLastDeploymentBucketName(String bucketName) {
LambdaFunctionDeploymentMetadata lastDeploy = getLastDeployment();
if (lastDeploy != null) {
lastDeploy.setAwsS3BucketName(bucketName);
}
}
@JsonIgnore
public String getLastDeploymentRoleName() {
LambdaFunctionDeploymentMetadata lastDeploy = getLastDeployment();
return lastDeploy == null ? null : lastDeploy.getAwsIamRoleName();
}
public void setLastDeploymentRoleName(String roleName) {
LambdaFunctionDeploymentMetadata lastDeploy = getLastDeployment();
if (lastDeploy != null) {
lastDeploy.setAwsIamRoleName(roleName);
}
}
/**
* Create the path to the target {@link LambdaFunctionDeploymentMetadata} in the Pojo if it is null and return it.
*/
private LambdaFunctionDeploymentMetadata getLastDeployment() {
if (lastDeploymentHandler != null) {
LambdaFunctionMetadata functionMetadata = handlerMetadata.get(lastDeploymentHandler);
if (functionMetadata == null) {
functionMetadata = new LambdaFunctionMetadata();
handlerMetadata.put(lastDeploymentHandler, functionMetadata);
}
if (functionMetadata.getDeployment() == null) {
functionMetadata.setDeployment(new LambdaFunctionDeploymentMetadata());
}
return functionMetadata.getDeployment();
}
return null;
}
/**
* Helper methods for getting and setting last invoke metadata according to {@link #lastInvokeHandler} field.
*/
@JsonIgnore
public boolean getLastInvokeSelectJsonInput() {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
return lastInvoke == null ? false : lastInvoke.isSelectJsonInput();
}
@JsonIgnore
public void setLastInvokeSelectJsonInput(boolean selectJsonInput) {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
if (lastInvoke != null) {
lastInvoke.setSelectJsonInput(selectJsonInput);
}
}
@JsonIgnore
public String getLastInvokeInput() {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
return lastInvoke == null ? "" : lastInvoke.getInvokeInput();
}
@JsonIgnore
public void setLastInvokeInput(String invokeInput) {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
if (lastInvoke != null) {
lastInvoke.setInvokeInput(invokeInput);
}
}
@JsonIgnore
public boolean getLastInvokeShowLiveLog() {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
return lastInvoke == null ? true : lastInvoke.isShowLiveLog();
}
@JsonIgnore
public void setLastInvokeShowLiveLog(boolean showLiveLog) {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
if (lastInvoke != null) {
lastInvoke.setShowLiveLog(showLiveLog);
}
}
@JsonIgnore
public boolean getLastInvokeSelectJsonFile() {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
return lastInvoke == null ? false : lastInvoke.isSelectJsonFile();
}
@JsonIgnore
public void setLastInvokeSelectJsonFile(boolean selectJsonFile) {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
if (lastInvoke != null) {
lastInvoke.setSelectJsonFile(selectJsonFile);
}
}
@JsonIgnore
public String getLastInvokeJsonFile() {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
return lastInvoke == null ? "" : lastInvoke.getInvokeJsonFile();
}
@JsonIgnore
public void setLastInvokeJsonFile(String invokeJsonFile) {
LambdaFunctionInvokeMetadata lastInvoke = getLastInvoke();
if (lastInvoke != null) {
lastInvoke.setInvokeJsonFile(invokeJsonFile);
}
}
/**
* Create the path to the target {@link LambdaFunctionInvokeMetadata} in the Pojo if it is null and return it.
*/
private LambdaFunctionInvokeMetadata getLastInvoke() {
if (lastInvokeHandler != null) {
LambdaFunctionMetadata functionMetadata = handlerMetadata.get(lastInvokeHandler);
if (functionMetadata == null) {
functionMetadata = new LambdaFunctionMetadata();
handlerMetadata.put(lastInvokeHandler, functionMetadata);
}
if (functionMetadata.getInvoke() == null) {
functionMetadata.setInvoke(new LambdaFunctionInvokeMetadata());
}
return functionMetadata.getInvoke();
}
return null;
}
public String getLastDeploymentHandler() {
return lastDeploymentHandler;
}
public void setLastDeploymentHandler(String lastDeploymentHandler) {
this.lastDeploymentHandler = lastDeploymentHandler;
}
public Map<String, LambdaFunctionMetadata> getHandlerMetadata() {
return handlerMetadata;
}
public String getLastInvokeHandler() {
return lastInvokeHandler;
}
public void setLastInvokeHandler(String lastInvokeHandler) {
this.lastInvokeHandler = lastInvokeHandler;
}
/**
* Cached settings for the operations to a Lambda function.
*/
public static class LambdaFunctionMetadata {
// Last deployment metadata
private LambdaFunctionDeploymentMetadata deployment;
// Last invoke metadata
private LambdaFunctionInvokeMetadata invoke;
public LambdaFunctionDeploymentMetadata getDeployment() {
return deployment;
}
public void setDeployment(LambdaFunctionDeploymentMetadata deployment) {
this.deployment = deployment;
}
public LambdaFunctionInvokeMetadata getInvoke() {
return invoke;
}
public void setInvoke(LambdaFunctionInvokeMetadata invoke) {
this.invoke = invoke;
}
}
/**
* Data Model for deploying a Lambda function.
*/
public static class LambdaFunctionDeploymentMetadata {
private String regionId;
private String awsLambdaFunctionName;
private String awsIamRoleName;
private String awsS3BucketName;
private int memory;
private int timeout;
public String getRegionId() {
return regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public String getAwsLambdaFunctionName() {
return awsLambdaFunctionName;
}
public void setAwsLambdaFunctionName(String awsLambdaFunctionName) {
this.awsLambdaFunctionName = awsLambdaFunctionName;
}
public String getAwsIamRoleName() {
return awsIamRoleName;
}
public void setAwsIamRoleName(String awsIamRoleName) {
this.awsIamRoleName = awsIamRoleName;
}
public String getAwsS3BucketName() {
return awsS3BucketName;
}
public void setAwsS3BucketName(String awsS3BucketName) {
this.awsS3BucketName = awsS3BucketName;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
}
/**
* Data model for invoking a Lambda function.
*/
public static class LambdaFunctionInvokeMetadata {
// Select a Json file as input
private boolean selectJsonFile = true;
private String invokeJsonFile;
// Select a Json content as input
private boolean selectJsonInput = false;
private String invokeInput;
private boolean showLiveLog = true;
public String getInvokeJsonFile() {
return invokeJsonFile == null ? "" : invokeJsonFile;
}
public void setInvokeJsonFile(String invokeJsonFile) {
this.invokeJsonFile = invokeJsonFile;
}
public boolean isSelectJsonInput() {
return selectJsonInput;
}
public void setSelectJsonInput(boolean selectJsonInput) {
this.selectJsonInput = selectJsonInput;
}
public String getInvokeInput() {
return invokeInput == null ? "" : invokeInput;
}
public void setInvokeInput(String invokeInput) {
this.invokeInput = invokeInput;
}
public boolean isSelectJsonFile() {
return selectJsonFile;
}
public void setSelectJsonFile(boolean selectJsonFile) {
this.selectJsonFile = selectJsonFile;
}
public boolean isShowLiveLog() {
return showLiveLog;
}
public void setShowLiveLog(boolean showLiveLog) {
this.showLiveLog = showLiveLog;
}
}
}
| 7,942 |
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/model/SelectOrInputStackDataModel.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.model;
import java.util.List;
import com.amazonaws.eclipse.cloudformation.CloudFormationUtils;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase;
import com.amazonaws.eclipse.core.model.SelectOrInputDataModel;
import com.amazonaws.services.cloudformation.model.StackSummary;
import com.amazonaws.util.StringUtils;
public class SelectOrInputStackDataModel extends SelectOrInputDataModel<StackSummary, AwsResourceScopeParamBase> {
private static final String RESOURCE_TYPE = "Stack";
private static final StackSummary LOADING = new StackSummary().withStackName("Loading...");
private static final StackSummary NONE_FOUND = new StackSummary().withStackName("None found");
private static final StackSummary ERROR = new StackSummary().withStackName("Error");
private String defaultStackNamePrefix;
public String getDefaultStackNamePrefix() {
return defaultStackNamePrefix;
}
public void setDefaultStackNamePrefix(String defaultStackNamePrefix) {
this.defaultStackNamePrefix = defaultStackNamePrefix;
}
public String getStackName() {
String existingStackName = getExistingResource() == null ? null : getExistingResource().getStackName();
String stackNameFromModel = isCreateNewResource() ? getNewResourceName()
: isSelectExistingResource() ? existingStackName
: null;
return StringUtils.isNullOrEmpty(stackNameFromModel) ? null : stackNameFromModel;
}
@Override
public StackSummary getLoadingItem() {
return LOADING;
}
@Override
public StackSummary getNotFoundItem() {
return NONE_FOUND;
}
@Override
public StackSummary getErrorItem() {
return ERROR;
}
@Override
public String getResourceType() {
return RESOURCE_TYPE;
}
@Override
public String getDefaultResourceName() {
return defaultStackNamePrefix + "-stack";
}
@Override
public List<StackSummary> loadAwsResources(AwsResourceScopeParamBase param) {
return CloudFormationUtils.listExistingStacks(param.getRegionId());
}
@Override
public String getResourceName(StackSummary stack) {
return stack.getStackName();
}
}
| 7,943 |
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/model/LambdaFunctionAliasesScopeParam.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.model;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam;
/**
* Parameter class for loading AWS Lambda Function Aliases.
*/
public class LambdaFunctionAliasesScopeParam extends AbstractAwsResourceScopeParam<LambdaFunctionAliasesScopeParam> {
private final String functionName;
public LambdaFunctionAliasesScopeParam(String accountId, String regionId, String functionName) {
super(accountId, regionId);
this.functionName = functionName;
}
@Override
public LambdaFunctionAliasesScopeParam copy() {
return new LambdaFunctionAliasesScopeParam(getAccountId(), getRegionId(), getFunctionName());
}
public String getFunctionName() {
return functionName;
}
}
| 7,944 |
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/model/SelectOrInputFunctionDataModel.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.model;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase;
import com.amazonaws.eclipse.lambda.ServiceApiUtils;
import java.util.List;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.model.SelectOrInputDataModel;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.model.FunctionConfiguration;
public class SelectOrInputFunctionDataModel extends SelectOrInputDataModel<FunctionConfiguration, AwsResourceScopeParamBase> {
private static final FunctionConfiguration LOADING = new FunctionConfiguration().withFunctionName("Loading...");
private static final FunctionConfiguration NOT_FOUND = new FunctionConfiguration().withFunctionName("Not Found");
private static final FunctionConfiguration ERROR = new FunctionConfiguration().withFunctionName("Error");
public String getFunctionName() {
return this.isCreateNewResource() ? this.getNewResourceName() :
this.isSelectExistingResource() ? this.getExistingResource().getFunctionName() : null;
}
@Override
public FunctionConfiguration getLoadingItem() {
return LOADING;
}
@Override
public FunctionConfiguration getNotFoundItem() {
return NOT_FOUND;
}
@Override
public FunctionConfiguration getErrorItem() {
return ERROR;
}
@Override
public String getResourceType() {
return "Lambda Function";
}
@Override
public String getDefaultResourceName() {
return "MyFunction";
}
@Override
public List<FunctionConfiguration> loadAwsResources(AwsResourceScopeParamBase param) {
AWSLambda lambdaClient = AwsToolkitCore.getClientFactory(param.getAccountId())
.getLambdaClientByRegion(param.getRegionId());
return ServiceApiUtils.getAllJavaFunctions(lambdaClient);
}
@Override
public String getResourceName(FunctionConfiguration resource) {
return resource.getFunctionName();
}
} | 7,945 |
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/model/SelectOrCreateBasicLambdaRoleDataModel.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.model;
import java.util.List;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase;
import com.amazonaws.eclipse.lambda.ServiceApiUtils;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.model.SelectOrCreateDataModel;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.Role;
public class SelectOrCreateBasicLambdaRoleDataModel extends SelectOrCreateDataModel<Role, AwsResourceScopeParamBase> {
private static final Role LOADING = new Role().withRoleName("Loading...");
private static final Role NONE_FOUND = new Role().withRoleName("None found");
private static final Role ERROR = new Role().withRoleName("Error Loading Roles");
@Override
public Role getLoadingItem() {
return LOADING;
}
@Override
public Role getNotFoundItem() {
return NONE_FOUND;
}
@Override
public Role getErrorItem() {
return ERROR;
}
@Override
public String getResourceType() {
return "IAM Role";
}
@Override
public String getDefaultResourceName() {
return "lambda-basic-execution";
}
@Override
public List<Role> loadAwsResources(AwsResourceScopeParamBase param) {
AmazonIdentityManagement iamClient = AwsToolkitCore.getClientFactory(param.getAccountId())
.getIAMClientByRegion(param.getRegionId());
return ServiceApiUtils.getAllLambdaRoles(iamClient);
}
@Override
public String getResourceName(Role resource) {
return resource.getRoleName();
}
} | 7,946 |
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/model/LambdaFunctionDataModel.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.model;
import com.amazonaws.eclipse.core.model.AbstractAwsToolkitDataModel;
import com.amazonaws.eclipse.lambda.blueprint.BlueprintsProvider;
import com.amazonaws.eclipse.lambda.blueprint.LambdaBlueprint;
import com.amazonaws.eclipse.lambda.blueprint.LambdaBlueprintsConfig;
import com.amazonaws.eclipse.lambda.project.template.data.LambdaBlueprintTemplateData;
/**
* Data model for Lambda function composite.
*/
public class LambdaFunctionDataModel extends AbstractAwsToolkitDataModel {
private static final String P_PACKAGE_NAME = "packageName";
public static final String P_CLASS_NAME = "className";
public static final String P_INPUT_TYPE = "inputType";
private static final LambdaBlueprintsConfig BLUEPRINTS_CONFIG = BlueprintsProvider.provideLambdaBlueprints();
private String className = "LambdaFunctionHandler";
private String packageName = "com.amazonaws.lambda.demo";
private LambdaBlueprint selectedBlueprint = BLUEPRINTS_CONFIG.getBlueprints()
.get(BLUEPRINTS_CONFIG.getDefaultBlueprint());
private String inputType = selectedBlueprint.getDisplayName();
public LambdaBlueprintTemplateData collectLambdaBlueprintTemplateData() {
if (getSelectedBlueprint() == null) {
throw new RuntimeException("The specified blueprint " + getInputType() + " doesn't exist!");
}
LambdaBlueprintTemplateData data = new LambdaBlueprintTemplateData();
data.setPackageName(getPackageName());
data.setHandlerClassName(getClassName());
data.setHandlerTestClassName(getClassName() + "Test");
data.setInputJsonFileName(getSelectedBlueprint().getTestJsonFile());
return data;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.setProperty(P_PACKAGE_NAME, packageName, this::getPackageName, (newValue) -> this.packageName = newValue);
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.setProperty(P_CLASS_NAME, className, this::getClassName, (newValue) -> this.className = newValue);
}
public String getInputType() {
return inputType;
}
public void setInputType(String inputType) {
this.selectedBlueprint = getLambdaBlueprint(inputType);
this.setProperty(P_INPUT_TYPE, inputType, this::getInputType, (newValue) -> this.inputType = newValue);
}
public LambdaBlueprint getSelectedBlueprint() {
return selectedBlueprint;
}
/**
* Return the LambdaBlueprint by display name.
*/
private static LambdaBlueprint getLambdaBlueprint(String displayName) {
for (LambdaBlueprint lambdaBlueprint : BLUEPRINTS_CONFIG.getBlueprints().values()) {
if (lambdaBlueprint.getDisplayName().equals(displayName)) {
return lambdaBlueprint;
}
}
return null;
}
}
| 7,947 |
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/model/package-info.java | /*
* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/**
* Collection of data models in Lambda plugin.
*/
package com.amazonaws.eclipse.lambda.model; | 7,948 |
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/model/SelectOrInputFunctionAliasDataModel.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.model;
import java.util.List;
import com.amazonaws.eclipse.core.model.SelectOrInputDataModel;
import com.amazonaws.eclipse.lambda.LambdaUtils;
import com.amazonaws.services.lambda.model.AliasConfiguration;
/**
* Data model for selecting or creating a new Lambda function alias.
*/
public class SelectOrInputFunctionAliasDataModel extends SelectOrInputDataModel<AliasConfiguration, LambdaFunctionAliasesScopeParam> {
private static final String RESOURCE_TYPE = "Function Alias";
private static final AliasConfiguration LOADING = new AliasConfiguration().withName("Loading...");
private static final AliasConfiguration NOT_FOUND = new AliasConfiguration().withName("Not Found");
private static final AliasConfiguration ERROR = new AliasConfiguration().withName("Error");
@Override
public AliasConfiguration getLoadingItem() {
return LOADING;
}
@Override
public AliasConfiguration getNotFoundItem() {
return NOT_FOUND;
}
@Override
public AliasConfiguration getErrorItem() {
return ERROR;
}
@Override
public String getResourceType() {
return RESOURCE_TYPE;
}
@Override
public String getDefaultResourceName() {
return "beta";
}
@Override
public List<AliasConfiguration> loadAwsResources(LambdaFunctionAliasesScopeParam param) {
return LambdaUtils.listFunctionAlias(param.getAccountId(), param.getRegionId(), param.getFunctionName());
}
@Override
public String getResourceName(AliasConfiguration alias) {
return alias.getName();
}
}
| 7,949 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/UploadFunctionWizard.java | /*
* Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.eclipse.lambda.upload.wizard;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.core.exceptions.AwsActionException;
import com.amazonaws.eclipse.core.plugin.AbstractAwsJobWizard;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.lambda.LambdaAnalytics;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.ProjectMetadataManager;
import com.amazonaws.eclipse.lambda.upload.wizard.model.UploadFunctionWizardDataModel;
import com.amazonaws.eclipse.lambda.upload.wizard.page.FunctionConfigurationPage;
import com.amazonaws.eclipse.lambda.upload.wizard.page.TargetFunctionSelectionPage;
import com.amazonaws.eclipse.lambda.upload.wizard.util.UploadFunctionUtil;
public class UploadFunctionWizard extends AbstractAwsJobWizard {
private final IProject project;
private final IJavaElement selectedJavaElement;
private UploadFunctionWizardDataModel dataModel;
public UploadFunctionWizard(IJavaElement selectedJavaElement) {
super("Upload Function to AWS Lambda");
this.project = selectedJavaElement.getJavaProject().getProject();
this.selectedJavaElement = selectedJavaElement;
initDataModel();
}
@Override
public void addPages() {
addPage(new TargetFunctionSelectionPage(dataModel));
addPage(new FunctionConfigurationPage(dataModel));
}
@Override
public boolean performCancel() {
LambdaAnalytics.trackUploadCanceled();
return true;
}
@Override
protected void initDataModel() {
// Load valid request handler classes
List<String> handlerClasses = new ArrayList<>();
handlerClasses.addAll(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;
}
// Load existing lambda project metadata
LambdaFunctionProjectMetadata md = null;
try {
md = ProjectMetadataManager.loadLambdaProjectMetadata(project);
} catch (IOException e) {
LambdaPlugin.getDefault().logInfo(
"Ignoring the existing metadata for project ["
+ project.getName()
+ "] since the content is invalid.");
}
dataModel = new UploadFunctionWizardDataModel(project, selectedJavaElement, handlerClasses, md);
if (md != null && md.getLastDeploymentHandler() != null) {
dataModel.setHandler(md.getLastDeploymentHandler());
}
}
@Override
protected IStatus doFinish(IProgressMonitor monitor) {
LambdaAnalytics.trackMetrics(dataModel.getFunctionDataModel().isCreateNewResource(),
dataModel.getRequestHandlerImplementerClasses().size());
monitor.beginTask("Uploading AWS Lambda Function Project [" +
project.getName() + "]", 100);
long startTime = System.currentTimeMillis();
try {
UploadFunctionUtil.performFunctionUpload(dataModel, monitor, 100);
} catch (Exception e) {
LambdaPlugin.getDefault().reportException(
"Failed to upload project to Lambda",
new AwsActionException(AwsToolkitMetricType.LAMBDA_UPLOAD_FUNCTION_WIZARD.getName(), e.getMessage(), e));
LambdaAnalytics.trackUploadFailed();
return Status.OK_STATUS;
}
LambdaPlugin.getDefault().getProjectChangeTracker()
.markProjectAsNotDirty(project);
LambdaAnalytics.trackUploadSucceeded();
LambdaAnalytics.trackUploadTotalTime(System.currentTimeMillis() - startTime);
monitor.done();
return Status.OK_STATUS;
}
@Override
protected String getJobTitle() {
return "Uploading function code to Lambda";
}
}
| 7,950 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/handler/UploadFunctionToLambdaCommandHandler.java | /*
* Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.eclipse.lambda.upload.wizard.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 org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.util.WorkbenchUtils;
import com.amazonaws.eclipse.lambda.LambdaAnalytics;
import com.amazonaws.eclipse.lambda.ui.LambdaJavaProjectUtil;
import com.amazonaws.eclipse.lambda.upload.wizard.UploadFunctionWizard;
public class UploadFunctionToLambdaCommandHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IJavaElement selectedJavaElement = LambdaJavaProjectUtil.getSelectedJavaElementFromCommandEvent(event);
if (selectedJavaElement != null) {
LambdaAnalytics.trackUploadWizardOpenedFromProjectContextMenu();
doUploadFunctionProjectToLambda(selectedJavaElement);
}
return null;
}
public static void doUploadFunctionProjectToLambda(IJavaElement selectedJavaElement) {
if (!WorkbenchUtils.openSaveFilesDialog(PlatformUI.getWorkbench())) {
return;
}
WizardDialog wizardDialog = new WizardDialog(
Display.getCurrent().getActiveShell(),
new UploadFunctionWizard(selectedJavaElement));
wizardDialog.open();
}
}
| 7,951 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/page/FunctionConfigurationPage.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.upload.wizard.page;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newComposite;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newFillingLabel;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLink;
import static com.amazonaws.eclipse.lambda.upload.wizard.model.FunctionConfigPageDataModel.P_CREATE_NEW_VERSION_ALIAS;
import static com.amazonaws.eclipse.lambda.upload.wizard.model.FunctionConfigPageDataModel.P_KMS_ENCRYPTION;
import static com.amazonaws.eclipse.lambda.upload.wizard.model.FunctionConfigPageDataModel.P_NONE_ENCRYPTION;
import static com.amazonaws.eclipse.lambda.upload.wizard.model.FunctionConfigPageDataModel.P_PUBLISH_NEW_VERSION;
import static com.amazonaws.eclipse.lambda.upload.wizard.model.FunctionConfigPageDataModel.P_S3_ENCRYPTION;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoProperties;
import org.eclipse.core.databinding.observable.ChangeEvent;
import org.eclipse.core.databinding.observable.IChangeListener;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.layout.GridDataFactory;
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.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase;
import com.amazonaws.eclipse.core.ui.SelectOrCreateBucketComposite;
import com.amazonaws.eclipse.core.ui.SelectOrCreateKmsKeyComposite;
import com.amazonaws.eclipse.core.widget.CheckboxComplex;
import com.amazonaws.eclipse.core.widget.RadioButtonComplex;
import com.amazonaws.eclipse.core.widget.TextComplex;
import com.amazonaws.eclipse.databinding.RangeValidator;
import com.amazonaws.eclipse.lambda.LambdaConstants;
import com.amazonaws.eclipse.lambda.model.LambdaFunctionAliasesScopeParam;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata.LambdaFunctionDeploymentMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata.LambdaFunctionMetadata;
import com.amazonaws.eclipse.lambda.ui.SelectOrCreateBasicLambdaRoleComposite;
import com.amazonaws.eclipse.lambda.ui.SelectOrInputFunctionAliasComposite;
import com.amazonaws.eclipse.lambda.upload.wizard.model.FunctionConfigPageDataModel;
import com.amazonaws.eclipse.lambda.upload.wizard.model.UploadFunctionWizardDataModel;
import com.amazonaws.services.lambda.model.FunctionConfiguration;
public class FunctionConfigurationPage extends WizardPageWithOnEnterHook {
private static final int MIN_MEMORY = 128;
private static final int MAX_MEMORY = 3008;
private static final int DEFAULT_MEMORY = 512;
private static final int MIN_TIMEOUT = 1;
private static final int MAX_TIMEOUT = 900;
private static final int DEFAULT_TIMEOUT = 15;
/* Data model and binding */
private UploadFunctionWizardDataModel dataModel;
private final DataBindingContext bindingContext;
private final AggregateValidationStatus aggregateValidationStatus;
/* Basic settings */
private Label functionNameLabel;
private TextComplex descriptionTextComplex;
/* Function execution role setting */
private SelectOrCreateBasicLambdaRoleComposite selectOrCreateBasicLambdaRoleComposite;
/* Function versioning and alias setting */
private CheckboxComplex publishNewVersionCheckbox;
private CheckboxComplex newVersionAliasCheckbox;
private SelectOrInputFunctionAliasComposite selectOrInputFunctionAliasComposite;
/* Target S3 bucket setting */
private SelectOrCreateBucketComposite selectOrCreateBucketComposite;
private RadioButtonComplex noneEncryptionButton;
private RadioButtonComplex amazonS3EncryptionButton;
private RadioButtonComplex awsKmsEncryptionButton;
private SelectOrCreateKmsKeyComposite selectOrCreateKmsKeyComposite;
/* Advanced settings */
private TextComplex memoryTextComplex;
private TextComplex timeoutTextComplex;
/**
* The validation status listener to be registered to the composite
*/
private final IChangeListener functionConfigValidationStatusListener = new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object observable = event.getObservable();
if (observable instanceof AggregateValidationStatus == false) return;
AggregateValidationStatus statusObservable = (AggregateValidationStatus)observable;
Object statusObservableValue = statusObservable.getValue();
if (statusObservableValue instanceof IStatus == false) return;
IStatus status = (IStatus)statusObservableValue;
boolean success = (status.getSeverity() == IStatus.OK);
if (success) {
setErrorMessage(null);
} else {
setErrorMessage(status.getMessage());
}
FunctionConfigurationPage.super.setPageComplete(success);
}
};
public FunctionConfigurationPage(UploadFunctionWizardDataModel dataModel) {
super("Function Configuration");
setTitle("Function Configuration");
setDescription("Configure this Lambda function and upload to AWS.");
setPageComplete(false);
this.dataModel = dataModel;
this.bindingContext = new DataBindingContext();
this.aggregateValidationStatus = new AggregateValidationStatus(
bindingContext, AggregateValidationStatus.MAX_SEVERITY);
}
@Override
public void createControl(Composite parent) {
ScrolledComposite scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL);
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
GridDataFactory.fillDefaults().grab(true, true).applyTo(scrolledComposite);
Composite functionConfigurationComposite = new Composite(scrolledComposite, SWT.NONE);
functionConfigurationComposite.setLayout(new GridLayout(1, false));
scrolledComposite.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
if (functionConfigurationComposite != null) {
Rectangle r = scrolledComposite.getClientArea();
scrolledComposite.setMinSize(functionConfigurationComposite.computeSize(r.width, SWT.DEFAULT));
}
}
});
scrolledComposite.setContent(functionConfigurationComposite);
createBasicSettingSection(functionConfigurationComposite);
createFunctionRoleSettingSection(functionConfigurationComposite);
createFunctionVersioningAndAliasSettingSection(functionConfigurationComposite);
createS3BucketSection(functionConfigurationComposite);
createAdvancedSettingSection(functionConfigurationComposite);
aggregateValidationStatus.addChangeListener(functionConfigValidationStatusListener);
setControl(scrolledComposite);
}
@Override
public void onEnterPage() {
refreshIamRole();
refreshFunctionAliases();
refreshS3Bucket();
refreshKmsKey();
functionNameLabel.setText(dataModel.getFunctionDataModel().getFunctionName());
if (dataModel.getFunctionDataModel().isSelectExistingResource()) {
FunctionConfiguration function = dataModel.getFunctionDataModel().getExistingResource();
descriptionTextComplex.setText(function.getDescription());
memoryTextComplex.setText(String.valueOf(function.getMemorySize()));
timeoutTextComplex.setText(String.valueOf(function.getTimeout()));
}
}
private void createBasicSettingSection(Composite parent) {
Group group = newGroup(parent, "Basic Settings");
group.setLayout(createSectionGroupLayout());
newLabel(group, "Name:");
functionNameLabel = newFillingLabel(group, "", 2);
descriptionTextComplex = TextComplex.builder(group,
bindingContext, PojoProperties.value(FunctionConfigPageDataModel.P_DESCRIPTION).observe(dataModel.getFunctionConfigPageDataModel()))
.createLabel(true)
.labelColSpan(1)
.labelValue("Description:")
.textColSpan(2)
.defaultValue(dataModel.getFunctionConfigPageDataModel().getDescription())
.textMessage("The description for the function (optional)")
.build();
}
private void createFunctionRoleSettingSection(Composite parent) {
Group group = newGroup(parent, "Function Role");
setItalicFont(newLink(
group,
LambdaConstants.webLinkListener,
"Select the IAM role that AWS Lambda can assume to execute the function on your behalf. <a href=\""
+ LambdaConstants.LAMBDA_EXECUTION_ROLE_DOC_URL
+ "\">Learn more</a> about Lambda execution roles.", 1, 100, 30));
selectOrCreateBasicLambdaRoleComposite = new SelectOrCreateBasicLambdaRoleComposite(
group, bindingContext, dataModel.getLambdaRoleDataModel());
}
private void createFunctionVersioningAndAliasSettingSection(Composite parent) {
Group group = newGroup(parent, "Function Versioning and Alias");
setItalicFont(newLink(
group,
LambdaConstants.webLinkListener,
"You can publish a new immutable version and an alias to that version whenever you have a new revision of the Lambda function. <a href=\""
+ LambdaConstants.LAMBDA_FUNCTION_VERSIONING_AND_ALIASES_URL
+ "\">Learn more</a> about Lambda function versioning and aliases.", 1, 100, 30));
publishNewVersionCheckbox = CheckboxComplex.builder()
.composite(group)
.dataBindingContext(bindingContext)
.defaultValue(false)
.labelValue("Publish new version")
.pojoObservableValue(PojoProperties.value(P_PUBLISH_NEW_VERSION).observe(dataModel.getFunctionConfigPageDataModel()))
.selectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onPublishNewVersionCheckboxSelected();
}
})
.build();
newVersionAliasCheckbox = CheckboxComplex.builder()
.composite(group)
.dataBindingContext(bindingContext)
.defaultValue(false)
.labelValue("Provide an alias to this new version")
.pojoObservableValue(PojoProperties.value(P_CREATE_NEW_VERSION_ALIAS).observe(dataModel.getFunctionConfigPageDataModel()))
.selectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onNewVersionAliasCheckboxSelected();
}
})
.build();
selectOrInputFunctionAliasComposite = new SelectOrInputFunctionAliasComposite(
group, bindingContext, dataModel.getFunctionAliasDataModel());
GridLayout gridLayout = (GridLayout)selectOrInputFunctionAliasComposite.getLayout();
gridLayout.marginLeft = 20;
selectOrInputFunctionAliasComposite.setLayout(gridLayout);
}
public void onPublishNewVersionCheckboxSelected() {
newVersionAliasCheckbox.getCheckbox().setEnabled(publishNewVersionCheckbox.getCheckbox().getSelection());
selectOrInputFunctionAliasComposite.setEnabled(publishNewVersionCheckbox.getCheckbox().getSelection() && newVersionAliasCheckbox.getCheckbox().getSelection());
}
private void onEncryptionRadioButtonsSelected() {
selectOrCreateKmsKeyComposite.setEnabled(awsKmsEncryptionButton.getRadioButton().getSelection());
}
private void onNewVersionAliasCheckboxSelected() {
selectOrInputFunctionAliasComposite.setEnabled(newVersionAliasCheckbox.getCheckbox().getSelection());
}
private void createS3BucketSection(Composite parent) {
Group group = newGroup(parent, "S3 Bucket for Function Code");
selectOrCreateBucketComposite = new SelectOrCreateBucketComposite(
group, bindingContext, dataModel.getS3BucketDataModel());
GridLayout gridLayout = (GridLayout) selectOrCreateBucketComposite.getLayout();
gridLayout.verticalSpacing = 0;
selectOrCreateBucketComposite.setLayout(gridLayout);
setItalicFont(newLink(group, LambdaConstants.webLinkListener,
"Upload Lambda zip file with encrytion to protect data at rest by using Amazon S3 master-key or by using AWS KMS master-key. <a href=\""
+ LambdaConstants.LAMBDA_FUNCTION_ENCRYPTION_URL
+ "\">Learn more</a> about Amazon S3 encryption.",
1, 100, 30));
Composite radioButtonComposite = newComposite(group, 1, 3, true);
SelectionAdapter selectAdapter = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onEncryptionRadioButtonsSelected();
}
};
noneEncryptionButton = createEncryptionButton(
radioButtonComposite,
P_NONE_ENCRYPTION,
dataModel.getFunctionConfigPageDataModel().isNoneEncryption(),
"None",
selectAdapter
);
amazonS3EncryptionButton = createEncryptionButton(
radioButtonComposite,
P_S3_ENCRYPTION,
dataModel.getFunctionConfigPageDataModel().isS3Encryption(),
"Amazon S3 master-key",
selectAdapter
);
awsKmsEncryptionButton = createEncryptionButton(
radioButtonComposite,
P_KMS_ENCRYPTION,
dataModel.getFunctionConfigPageDataModel().isKmsEncryption(),
"AWS KMS master-key",
selectAdapter
);
selectOrCreateKmsKeyComposite = new SelectOrCreateKmsKeyComposite(
group, bindingContext, dataModel.getKmsKeyDataModel());
}
private void createAdvancedSettingSection(Composite parent) {
Group group = newGroup(parent, "Advanced Settings");
group.setLayout(createSectionGroupLayout());
String memoryErrMsg = String.format(
"Please enter a memory size within the range of [%d, %d]",
MIN_MEMORY, MAX_MEMORY);
String timeoutErrMsg = String.format(
"Please enter a timeout within the range of [%d, %d]",
MIN_TIMEOUT, MAX_TIMEOUT);
memoryTextComplex = TextComplex.builder(group,
bindingContext, PojoProperties.value(FunctionConfigPageDataModel.P_MEMORY).observe(dataModel.getFunctionConfigPageDataModel()))
.addValidator(new RangeValidator(memoryErrMsg,
MIN_MEMORY, MAX_MEMORY))
.createLabel(true)
.defaultValue(Integer.toString(DEFAULT_MEMORY))
.labelColSpan(1)
.labelValue("Memory (MB):")
.textColSpan(2)
.build();
timeoutTextComplex = TextComplex.builder(group,
bindingContext, PojoProperties.value(FunctionConfigPageDataModel.P_TIMEOUT).observe(dataModel.getFunctionConfigPageDataModel()))
.addValidator(new RangeValidator(timeoutErrMsg,
MIN_TIMEOUT, MAX_TIMEOUT))
.createLabel(true)
.defaultValue(Integer.toString(DEFAULT_TIMEOUT))
.labelColSpan(1)
.labelValue("Timeout (s):")
.textColSpan(2)
.build();
}
private RadioButtonComplex createEncryptionButton(Composite composite, String propertyName, boolean defaultValue, String labelValue, SelectionListener listener) {
return RadioButtonComplex.builder()
.composite(composite)
.dataBindingContext(bindingContext)
.pojoObservableValue(PojoProperties.value(propertyName).observe(dataModel.getFunctionConfigPageDataModel()))
.defaultValue(defaultValue)
.labelValue(labelValue)
.selectionListener(listener)
.build();
}
private GridLayout createSectionGroupLayout() {
GridLayout layout = new GridLayout(3, true);
layout.marginWidth = 15;
return layout;
}
private String getLastDeploymentBucketName() {
String handler = dataModel.getHandler();
String defaultS3Bucket = null;
LambdaFunctionProjectMetadata projectMetadata = dataModel.getProjectMetadataBeforeUpload();
if (projectMetadata != null && projectMetadata.getHandlerMetadata().get(handler) != null) {
LambdaFunctionMetadata functionMetadata = projectMetadata.getHandlerMetadata().get(handler);
LambdaFunctionDeploymentMetadata deployment = functionMetadata.getDeployment();
if (deployment != null) {
defaultS3Bucket = deployment.getAwsS3BucketName();
}
}
return defaultS3Bucket;
}
private String getDefaultIamRole() {
FunctionConfiguration function = dataModel.getFunctionDataModel().getExistingResource();
String defaultRoleName = null;
if (dataModel.getFunctionDataModel().isSelectExistingResource() && function != null) {
defaultRoleName = function.getRole().split("/")[1];
} else {
defaultRoleName = dataModel.getProjectMetadataBeforeUpload() == null
? null
: this.dataModel.getProjectMetadataBeforeUpload()
.getLastDeploymentRoleName();
}
return defaultRoleName;
}
private void refreshFunctionAliases() {
selectOrInputFunctionAliasComposite.refreshComposite(
new LambdaFunctionAliasesScopeParam(
AwsToolkitCore.getDefault().getCurrentAccountId(),
dataModel.getRegionDataModel().getRegion().getId(),
dataModel.getFunctionDataModel().getFunctionName()),
null);
onPublishNewVersionCheckboxSelected();
}
/*
* Async loading of S3 buckets. S3 buckets might be loaded multiple times
* since it depends on the current region being selected
*/
private void refreshS3Bucket() {
selectOrCreateBucketComposite.refreshComposite(new AwsResourceScopeParamBase(
AwsToolkitCore.getDefault().getCurrentAccountId(),
dataModel.getRegionDataModel().getRegion().getId()), getLastDeploymentBucketName());
}
private void refreshKmsKey() {
selectOrCreateKmsKeyComposite.refreshComposite(new AwsResourceScopeParamBase(
AwsToolkitCore.getDefault().getCurrentAccountId(),
dataModel.getRegionDataModel().getRegion().getId()), null);
onEncryptionRadioButtonsSelected();
}
private void refreshIamRole() {
selectOrCreateBasicLambdaRoleComposite.refreshComposite(new AwsResourceScopeParamBase(
AwsToolkitCore.getDefault().getCurrentAccountId(),
dataModel.getRegionDataModel().getRegion().getId()), getDefaultIamRole());
}
private static Label newLabel(Composite parent, String text) {
Label label = new Label(parent, SWT.NONE);
label.setText(text);
return label;
}
/*
* Italic font resource
*/
private List<Font> italicFontList = new ArrayList<>();
private void setItalicFont(Control control) {
FontData[] fontData = control.getFont().getFontData();
for (FontData fd : fontData) {
fd.setStyle(SWT.ITALIC);
}
Font italicFont = new Font(Display.getDefault(), fontData);
control.setFont(italicFont);
italicFontList.add(italicFont);
}
@Override
public void dispose() {
italicFontList.forEach(Font::dispose);
super.dispose();
}
} | 7,952 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/page/WizardPageWithOnEnterHook.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.upload.wizard.page;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
/**
* To emulate onEnter event for JFace wizard page.
* http://www.eclipse.org/forums/index.php/t/88927/
*/
abstract class WizardPageWithOnEnterHook extends WizardPage {
protected WizardPageWithOnEnterHook(String pageName) {
super(pageName);
}
protected abstract void onEnterPage();
@Override
public final boolean canFlipToNextPage() {
return isPageComplete() && getNextPage(false) != null;
}
@Override
public final IWizardPage getNextPage() {
return getNextPage(true);
}
private IWizardPage getNextPage(boolean aboutToShow) {
IWizardPage nextPage = super.getNextPage();
if (aboutToShow && (nextPage instanceof WizardPageWithOnEnterHook)) {
((WizardPageWithOnEnterHook) nextPage).onEnterPage();
}
return nextPage;
}
}
| 7,953 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/page/TargetFunctionSelectionPage.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.upload.wizard.page;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newComposite;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup;
import static com.amazonaws.eclipse.lambda.LambdaAnalytics.trackRegionComboChangeSelection;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoProperties;
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.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
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.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.core.ui.RegionComposite;
import com.amazonaws.eclipse.core.widget.ComboViewerComplex;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata.LambdaFunctionDeploymentMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata.LambdaFunctionMetadata;
import com.amazonaws.eclipse.lambda.ui.SelectOrInputFunctionComposite;
import com.amazonaws.eclipse.lambda.upload.wizard.model.UploadFunctionWizardDataModel;
public class TargetFunctionSelectionPage extends WizardPageWithOnEnterHook {
/* Data model and binding */
private final UploadFunctionWizardDataModel dataModel;
private final DataBindingContext bindingContext;
private final AggregateValidationStatus aggregateValidationStatus;
/* UI widgets */
private ComboViewerComplex<String> handlerComboViewerComplex;
private RegionComposite regionComposite;
private SelectOrInputFunctionComposite functionComposite;
public TargetFunctionSelectionPage(UploadFunctionWizardDataModel dataModel) {
super("Select Target Lambda Function");
setTitle("Select Target Lambda Function");
setDescription("Choose the region and the target AWS Lambda function you want to create or update for your local lambda handler.");
setPageComplete(false);
this.dataModel = dataModel;
this.bindingContext = new DataBindingContext();
this.aggregateValidationStatus = new AggregateValidationStatus(
bindingContext, AggregateValidationStatus.MAX_SEVERITY);
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
createHandlerAndRegionSection(composite);
createJavaFunctionSection(composite);
initializeValidators();
// Force refresh function list
onHandlerSelectionChange();
setControl(composite);
setPageComplete(false);
}
private void createHandlerAndRegionSection(Composite composite) {
Group handlerAndRegionGroup = newGroup(composite, "Select Lambda Handler and Target Region");
handlerAndRegionGroup.setLayout(new GridLayout(1, false));
Composite handlerComposite = newComposite(handlerAndRegionGroup, 1, 2);
handlerComboViewerComplex = ComboViewerComplex.<String>builder()
.composite(handlerComposite)
.bindingContext(bindingContext)
.pojoObservableValue(PojoProperties.value(UploadFunctionWizardDataModel.P_HANDLER).observe(dataModel))
.defaultItem(dataModel.getHandler())
.labelValue("Select the Handler:")
.addListeners(e -> onHandlerSelectionChange())
.labelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
return element == null ? "" : element.toString();
}
})
.items(dataModel.getRequestHandlerImplementerClasses())
.build();
regionComposite = RegionComposite.builder()
.parent(handlerAndRegionGroup)
.bindingContext(bindingContext)
.dataModel(dataModel.getRegionDataModel())
.labelValue("Select the AWS Region:")
.serviceName(ServiceAbbreviations.LAMBDA)
.addListener(e -> {
trackRegionComboChangeSelection();
onRegionSelectionChange();
})
.build();
}
private void createJavaFunctionSection(Composite composite) {
Group javaFunctionGroup = newGroup(composite, "Select or Create a Lambda Function:");
javaFunctionGroup.setLayout(new GridLayout(1, false));
functionComposite = new SelectOrInputFunctionComposite(
javaFunctionGroup, bindingContext, dataModel.getFunctionDataModel());
}
private void onHandlerSelectionChange() {
String handler = dataModel.getHandler();
LambdaFunctionProjectMetadata projectMetadata = dataModel.getProjectMetadataBeforeUpload();
if (projectMetadata != null && projectMetadata.getHandlerMetadata().get(handler) != null) {
LambdaFunctionMetadata functionMetadata = projectMetadata.getHandlerMetadata().get(handler);
LambdaFunctionDeploymentMetadata deployment = functionMetadata.getDeployment();
if (deployment != null) {
regionComposite.selectAwsRegion(RegionUtils.getRegion(deployment.getRegionId()));
}
}
onRegionSelectionChange();
}
private void onRegionSelectionChange() {
String handler = dataModel.getHandler();
String defaultFunctionName = null;
LambdaFunctionProjectMetadata projectMetadata = dataModel.getProjectMetadataBeforeUpload();
if (projectMetadata != null && projectMetadata.getHandlerMetadata().get(handler) != null) {
LambdaFunctionMetadata functionMetadata = projectMetadata.getHandlerMetadata().get(handler);
LambdaFunctionDeploymentMetadata deployment = functionMetadata.getDeployment();
if (deployment != null) {
defaultFunctionName = deployment.getAwsLambdaFunctionName();
}
}
functionComposite.refreshComposite(new AwsResourceScopeParamBase(
AwsToolkitCore.getDefault().getCurrentAccountId(),
dataModel.getRegionDataModel().getRegion().getId()), defaultFunctionName);
}
private void initializeValidators() {
// Bind the validation status to the wizard page message
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent arg0) {
Object value = aggregateValidationStatus.getValue();
if (value instanceof IStatus == false) return;
IStatus status = (IStatus)value;
boolean success = (status.getSeverity() == IStatus.OK);
if (success) {
setErrorMessage(null);
} else {
setErrorMessage(status.getMessage());
}
TargetFunctionSelectionPage.super.setPageComplete(success);
}
});
}
@Override
protected void onEnterPage() {
}
}
| 7,954 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/util/LambdaFunctionJarBuilder.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.upload.wizard.util;
import java.io.File;
import java.util.zip.ZipFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarBuilder;
import org.eclipse.jdt.ui.jarpackager.IManifestProvider;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
public class LambdaFunctionJarBuilder extends FatJarBuilder {
private static final String LAMBDA_FUNCTINO_JAR_BUILDER_ID = LambdaFunctionJarBuilder.class.getName();
public LambdaFunctionJarBuilder() {
}
@Override
public String getId() {
return LAMBDA_FUNCTINO_JAR_BUILDER_ID;
}
@Override
public IManifestProvider getManifestProvider() {
// we don't need to bundle manifest file for the function zip file
return null;
}
@Override
public void writeArchive(ZipFile zip, IProgressMonitor monitor) {
String zipPath = zip.getName();
File zipFile = new File(zipPath);
String zipName = zipFile.getName();
try {
getJarWriter().write(zipFile, new Path("lib/" + zipName));
} catch (CoreException e) {
LambdaPlugin.getDefault().reportException(
"Failed to bundle dependency into the function jar file. " + zipPath, e);
}
}
@Override
public String getManifestClasspath() {
return null;
}
@Override
public boolean isMergeManifests() {
return false;
}
@Override
public boolean isRemoveSigners() {
return true;
}
}
| 7,955 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/util/FunctionJarExportHelper.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.upload.wizard.util;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
@SuppressWarnings("restriction")
public class FunctionJarExportHelper {
public static File exportProjectToJarFile(IProject project, boolean logInfo) {
JarPackageData jarExportOps = new JarPackageData();
jarExportOps.setExportJavaFiles(false);
jarExportOps.setExportClassFiles(true);
jarExportOps.setIncludeDirectoryEntries(true);
jarExportOps.setUsesManifest(false);
jarExportOps.setOverwrite(true);
jarExportOps.setJarBuilder(new LambdaFunctionJarBuilder());
try {
Object[] elements = getElementsToExport(project);
jarExportOps.setElements(elements);
// prefix should be at least three characters long
File jarFile = File.createTempFile(project.getName() + "-lambda", ".zip");
jarFile.deleteOnExit();
jarExportOps.setJarLocation(new Path(jarFile.getAbsolutePath()));
if (logInfo) {
LambdaPlugin.getDefault().logInfo(
String.format("Exporting project [%s] to %s",
project.getName(), jarFile.getAbsolutePath()));
}
IJarExportRunnable runnable = jarExportOps
.createJarExportRunnable(null);
runnable.run(null);
if (logInfo) {
LambdaPlugin.getDefault().logInfo("Project exported to " + jarFile.getAbsolutePath());
}
return jarFile;
} catch (Exception e) {
LambdaPlugin.getDefault().reportException(
String.format("Unable to export project [%s] to jar file",
project.getName()), e);
return null;
}
}
private static Object[] getElementsToExport(IProject project)
throws CoreException {
IJavaProject javaProj = JavaCore.create(project);
try {
ILaunchConfiguration launchConfiguration = createLaunchConfigurationForProject(javaProj);
return getSelectedElementsWithoutContainedChildren(launchConfiguration);
} catch (CoreException e) {
LambdaPlugin.getDefault().logWarning(
"Unable to resolve dependencies of project "
+ project.getName(), e);
// Fall back to export all the file resource inside the project
return project.members(IResource.FILE);
}
}
private static ILaunchConfiguration createLaunchConfigurationForProject(
IJavaProject javaProject) throws CoreException {
DebugPlugin plugin = DebugPlugin.getDefault();
ILaunchManager manager = plugin.getLaunchManager();
ILaunchConfigurationType javaAppType = manager
.getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION);
ILaunchConfigurationWorkingCopy wc = javaAppType.newInstance(null, "temp-config");
wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
javaProject.getElementName());
return wc;
}
/*
* ********************************************************************************************
* START OF SOURCE EXTRACTED FROM org.eclipse.jdt.internal.ui.jarpackager.JarPackageWizardPage
* ********************************************************************************************
*/
private static Object[] getSelectedElementsWithoutContainedChildren(ILaunchConfiguration launchconfig) throws CoreException {
if (launchconfig == null)
return new Object[0];
String projectName= launchconfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
IPath[] classpath= getClasspath(launchconfig);
IPackageFragmentRoot[] classpathResources= getRequiredPackageFragmentRoots(classpath, projectName);
return classpathResources;
}
private static IPath[] getClasspath(ILaunchConfiguration configuration) throws CoreException {
IRuntimeClasspathEntry[] entries= JavaRuntime.computeUnresolvedRuntimeClasspath(configuration);
entries= JavaRuntime.resolveRuntimeClasspath(entries, configuration);
ArrayList<IPath> userEntries= new ArrayList<>(entries.length);
for (int i= 0; i < entries.length; i++) {
if (entries[i].getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES) {
String location= entries[i].getLocation();
if (location != null) {
IPath entry= Path.fromOSString(location);
if (!userEntries.contains(entry)) {
userEntries.add(entry);
}
}
}
}
return userEntries.toArray(new IPath[userEntries.size()]);
}
/**
* @param classpathEntries the path to the package fragment roots
* @param projectName the root of the project dependency tree
* @return all package fragment roots corresponding to each classpath entry start the search at project with projectName
*/
private static IPackageFragmentRoot[] getRequiredPackageFragmentRoots(IPath[] classpathEntries, final String projectName) {
HashSet<IPackageFragmentRoot> result= new HashSet<>();
IJavaProject[] searchOrder= getProjectSearchOrder(projectName);
for (int i= 0; i < classpathEntries.length; i++) {
IPath entry= classpathEntries[i];
IPackageFragmentRoot[] elements= findRootsForClasspath(entry, searchOrder);
if (elements != null) {
for (int j= 0; j < elements.length; j++) {
result.add(elements[j]);
}
}
}
return result.toArray(new IPackageFragmentRoot[result.size()]);
}
private static IJavaProject[] getProjectSearchOrder(String projectName) {
ArrayList<String> projectNames= new ArrayList<>();
projectNames.add(projectName);
int nextProject= 0;
while (nextProject < projectNames.size()) {
String nextProjectName= projectNames.get(nextProject);
IJavaProject jproject= getJavaProject(nextProjectName);
if (jproject != null) {
try {
String[] childProjectNames= jproject.getRequiredProjectNames();
for (int i= 0; i < childProjectNames.length; i++) {
if (!projectNames.contains(childProjectNames[i])) {
projectNames.add(childProjectNames[i]);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
nextProject+= 1;
}
ArrayList<IJavaProject> result= new ArrayList<>();
for (int i= 0, size= projectNames.size(); i < size; i++) {
String name= projectNames.get(i);
IJavaProject project= getJavaProject(name);
if (project != null)
result.add(project);
}
return result.toArray(new IJavaProject[result.size()]);
}
private static IJavaProject getJavaProject(String projectName) {
IProject project= ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (project == null)
return null;
IJavaProject result= JavaCore.create(project);
if (result == null)
return null;
if (!result.exists())
return null;
return result;
}
private static IPackageFragmentRoot[] findRootsForClasspath(IPath entry, IJavaProject[] searchOrder) {
for (int i= 0; i < searchOrder.length; i++) {
IPackageFragmentRoot[] elements= findRootsInProject(entry, searchOrder[i]);
if (elements.length != 0) {
return elements;
}
}
return null;
}
private static IPackageFragmentRoot[] findRootsInProject(IPath entry, IJavaProject project) {
ArrayList<IPackageFragmentRoot> result= new ArrayList<>();
try {
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot packageFragmentRoot= roots[i];
if (isRootAt(packageFragmentRoot, entry))
result.add(packageFragmentRoot);
}
} catch (Exception e) {
JavaPlugin.log(e);
}
return result.toArray(new IPackageFragmentRoot[result.size()]);
}
private static boolean isRootAt(IPackageFragmentRoot root, IPath entry) {
try {
IClasspathEntry cpe= root.getRawClasspathEntry();
if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath outputLocation= cpe.getOutputLocation();
if (outputLocation == null)
outputLocation= root.getJavaProject().getOutputLocation();
IPath location= ResourcesPlugin.getWorkspace().getRoot().findMember(outputLocation).getLocation();
if (entry.equals(location))
return true;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
IResource resource= root.getResource();
if (resource != null && entry.equals(resource.getLocation()))
return true;
IPath path= root.getPath();
if (path != null && entry.equals(path))
return true;
return false;
}
/*
* ********************************************************************************************
* END OF SOURCE EXTRACTED FROM org.eclipse.jdt.internal.ui.jarpackager.JarPackageWizardPage
* ********************************************************************************************
*/
}
| 7,956 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/util/UploadFunctionUtil.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.upload.wizard.util;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.lambda.LambdaAnalytics;
import com.amazonaws.eclipse.lambda.LambdaConstants;
import com.amazonaws.eclipse.lambda.LambdaPlugin;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata;
import com.amazonaws.eclipse.lambda.project.metadata.ProjectMetadataManager;
import com.amazonaws.eclipse.lambda.project.wizard.util.FunctionProjectUtil;
import com.amazonaws.eclipse.lambda.upload.wizard.model.UploadFunctionWizardDataModel;
import com.amazonaws.services.kms.model.KeyListEntry;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.model.CreateAliasRequest;
import com.amazonaws.services.lambda.model.CreateFunctionRequest;
import com.amazonaws.services.lambda.model.CreateFunctionResult;
import com.amazonaws.services.lambda.model.FunctionCode;
import com.amazonaws.services.lambda.model.UpdateAliasRequest;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeRequest;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeResult;
import com.amazonaws.services.lambda.model.UpdateFunctionConfigurationResult;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams;
public class UploadFunctionUtil {
private static final String LAMBDA_REQUEST_HANDLER_INTERFACE = "com.amazonaws.services.lambda.runtime.RequestHandler";
private static final String LAMBDA_REQUEST_STREAM_HANDLER_INTERFACE = "com.amazonaws.services.lambda.runtime.RequestStreamHandler";
public static void performFunctionUpload(
UploadFunctionWizardDataModel dataModel,
final IProgressMonitor monitor, int totalUnitOfWork)
throws IOException {
monitor.subTask("Exporting Lambda function project...");
//TODO provide an option to generate the Jar with Maven
File jarFile = FunctionJarExportHelper.exportProjectToJarFile(
dataModel.getProject(), true);
monitor.worked((int)(totalUnitOfWork * 0.2));
AWSLambda client = AwsToolkitCore.getClientFactory().getLambdaClientByRegion(
dataModel.getRegionDataModel().getRegion().getId());
monitor.subTask("Uploading function code to S3...");
String bucketName = dataModel.getS3BucketDataModel().getBucketName();
String randomKeyName = dataModel.getFunctionDataModel().getFunctionName();
randomKeyName += ".zip";
AmazonS3 s3 = AwsToolkitCore.getClientFactory()
.getS3ClientForBucket(bucketName);
LambdaAnalytics.trackExportedJarSize(jarFile.length());
long startTime = System.currentTimeMillis();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, randomKeyName, jarFile);
if (dataModel.getFunctionConfigPageDataModel().isS3Encryption()) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
putObjectRequest.setMetadata(metadata);
} else if (dataModel.getFunctionConfigPageDataModel().isKmsEncryption()) {
KeyListEntry key = dataModel.getKmsKeyDataModel().getExistingResource().getKey();
putObjectRequest.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(key.getKeyId()));
}
s3.putObject(putObjectRequest);
long uploadTime = System.currentTimeMillis() - startTime;
LambdaAnalytics.trackUploadS3BucketTime(uploadTime);
LambdaAnalytics.trackUploadS3BucketSpeed((double)jarFile.length() / (double)uploadTime);
monitor.worked((int)(totalUnitOfWork * 0.4));
String functionName;
String functionArn;
String functionVersion;
if (dataModel.getFunctionDataModel().isCreateNewResource()) {
monitor.subTask("Creating new Lambda function...");
CreateFunctionRequest createReq = dataModel.toCreateFunctionRequest();
createReq.setCode(new FunctionCode()
.withS3Bucket(bucketName)
.withS3Key(randomKeyName));
CreateFunctionResult createResult = client
.createFunction(createReq);
functionName = createResult.getFunctionName();
functionArn = createResult.getFunctionArn();
functionVersion = createResult.getVersion();
LambdaPlugin.getDefault().logInfo(
"Function " + functionArn + " created.");
} else {
monitor.subTask("Updating function configuration");
UpdateFunctionConfigurationResult updateConfigResult = client
.updateFunctionConfiguration(dataModel
.toUpdateFunctionConfigRequest());
functionName = updateConfigResult.getFunctionName();
updateConfigResult.getVersion();
monitor.subTask("Updating function code");
UpdateFunctionCodeResult updateFunctionCodeResult = client.updateFunctionCode(new UpdateFunctionCodeRequest()
.withFunctionName(functionName)
.withS3Bucket(bucketName)
.withS3Key(randomKeyName)
.withPublish(dataModel.getFunctionConfigPageDataModel().isPublishNewVersion()));
functionArn = updateConfigResult.getFunctionArn();
functionVersion = updateFunctionCodeResult.getVersion();
LambdaPlugin.getDefault().logInfo(
"Function " + functionArn + " updated.");
}
if (dataModel.getFunctionConfigPageDataModel().isPublishNewVersion()
&& dataModel.getFunctionConfigPageDataModel().isCreateNewVersionAlias()) {
if (dataModel.getFunctionAliasDataModel().isCreateNewResource()) {
client.createAlias(new CreateAliasRequest()
.withFunctionName(functionName)
.withFunctionVersion(functionVersion)
.withName(dataModel.getFunctionAliasDataModel().getNewResourceName()));
} else if (dataModel.getFunctionAliasDataModel().isSelectExistingResource()) {
client.updateAlias(new UpdateAliasRequest()
.withFunctionName(functionName)
.withName(dataModel.getFunctionAliasDataModel().getExistingResource().getName())
.withFunctionVersion(functionVersion));
}
}
monitor.worked((int)(totalUnitOfWork * 0.2));
monitor.subTask("Saving project metadata");
LambdaFunctionProjectMetadata md = dataModel.getProjectMetadataBeforeUpload();
md.setLastDeploymentHandler(dataModel.getHandler());
md.setLastDeploymentRegion(dataModel.getRegionDataModel().getRegion().getId());
md.setLastDeploymentFunctionName(functionName);
md.setLastDeploymentBucketName(bucketName);
md.setLastDeploymentRoleName(dataModel.getLambdaRoleDataModel().getExistingResource().getRoleName());
ProjectMetadataManager.saveLambdaProjectMetadata(dataModel.getProject(), md);
FunctionProjectUtil.refreshProject(dataModel.getProject());
// Refresh the decorator
Display.getDefault().asyncExec( () -> {
PlatformUI.getWorkbench().getDecoratorManager().update(LambdaConstants.LAMBDA_PROJECT_DECORATOR_ID);
});
monitor.worked((int)(totalUnitOfWork * 0.2));
LambdaPlugin.getDefault().logInfo("Project metadata saved.");
LambdaPlugin.getDefault().logInfo("Upload complete! Funtion arn " + functionArn);
}
public static Set<String> findValidHandlerClass(IProject project) {
return findAllConcreteSubTypes(project, LAMBDA_REQUEST_HANDLER_INTERFACE);
}
public static Set<String> findValidStreamHandlerClass(IProject project) {
return findAllConcreteSubTypes(project, LAMBDA_REQUEST_STREAM_HANDLER_INTERFACE);
}
/**
* @see #findValidLambdaHandlerClass(IJavaProject, String)
*/
private static Set<String> findAllConcreteSubTypes(IProject project, final String lambdaHandlerClass) {
boolean isJavaProject = false;
try {
isJavaProject = project.hasNature(JavaCore.NATURE_ID);
} catch (Exception e) {
LambdaPlugin.getDefault()
.logWarning("Failed read the project nature of "
+ project.getName(), e);
}
if (isJavaProject) {
IJavaProject javaProject = JavaCore.create(project);
return findValidLambdaHandlerClass(javaProject, lambdaHandlerClass);
}
return Collections.emptySet();
}
/**
* @return a list of FQCNs of the concrete classes within the specified
* project that implement the specified lambda request handler interface, or
* null if any error occurred during the search.
*/
private static Set<String> findValidLambdaHandlerClass(IJavaProject javaProject, final String lambdaHandlerClass) {
try {
IType type = javaProject.findType(lambdaHandlerClass);
if (type == null) {
return Collections.emptySet();
}
ITypeHierarchy typeHierarchy = type.newTypeHierarchy(javaProject, null);
Set<String> allHandlerImplementers = new HashSet<>();
IType[] allSubtypes = typeHierarchy.getAllSubtypes(type);
// filter out abstract class and interfaces
for (IType subtype : allSubtypes) {
if (!subtype.isInterface() && !isAbstract(subtype)) {
allHandlerImplementers.add(subtype.getFullyQualifiedName());
}
}
return allHandlerImplementers;
} catch (JavaModelException e) {
LambdaPlugin.getDefault()
.logWarning("Failed to search for lambda request handler implementer classes ",
e);
return null;
}
}
private static boolean isAbstract(IType type) {
try {
return Flags.isAbstract(type.getFlags());
} catch (JavaModelException e) {
return false;
}
}
}
| 7,957 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/editoraction/UploadToLambdaAction.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.upload.wizard.editoraction;
import org.eclipse.jface.action.IAction;
import com.amazonaws.eclipse.lambda.LambdaAnalytics;
import com.amazonaws.eclipse.lambda.upload.wizard.handler.UploadFunctionToLambdaCommandHandler;
public class UploadToLambdaAction extends AbstractLambdaEditorAction {
@Override
public void run(IAction action) {
LambdaAnalytics.trackUploadWizardOpenedFromEditorContextMenu();
UploadFunctionToLambdaCommandHandler
.doUploadFunctionProjectToLambda(selectedJavaElement);
}
} | 7,958 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/editoraction/RunOnLambdaAction.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.upload.wizard.editoraction;
import org.eclipse.jface.action.IAction;
import com.amazonaws.eclipse.lambda.invoke.handler.InvokeFunctionHandler;
public class RunOnLambdaAction extends AbstractLambdaEditorAction {
@Override
public void run(IAction action) {
InvokeFunctionHandler.invokeLambdaFunctionProject(selectedJavaElement);
}
}
| 7,959 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/editoraction/AbstractLambdaEditorAction.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.upload.wizard.editoraction;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
@SuppressWarnings("restriction")
public abstract class AbstractLambdaEditorAction implements IObjectActionDelegate {
protected IJavaElement selectedJavaElement;
@Override
public void selectionChanged(IAction action, ISelection selection) {
}
@Override
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
if (!(targetPart instanceof JavaEditor)) {
return;
}
JavaEditor javaEditor = (JavaEditor)targetPart;
selectedJavaElement = JavaUI.getEditorInputJavaElement(javaEditor.getEditorInput());
}
}
| 7,960 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/dialog/CreateBasicLambdaRoleDialog.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.upload.wizard.dialog;
import java.util.UUID;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase;
import com.amazonaws.eclipse.core.ui.dialogs.AbstractInputDialog;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.AttachRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.CreatePolicyRequest;
import com.amazonaws.services.identitymanagement.model.CreateRoleRequest;
import com.amazonaws.services.identitymanagement.model.CreateRoleResult;
import com.amazonaws.services.identitymanagement.model.Role;
public class CreateBasicLambdaRoleDialog extends AbstractInputDialog<Role> {
private final AwsResourceScopeParamBase param;
private static final String BASIC_ROLE_POLICY =
"{" +
"\"Version\": \"2012-10-17\"," +
"\"Statement\": [" +
"{" +
"\"Effect\": \"Allow\"," +
"\"Action\": [" +
"\"logs:*\"" +
"]," +
"\"Resource\": \"arn:aws:logs:*:*:*\"" +
"}" +
"]" +
"}";
private static final String ASSUME_ROLE_POLICY =
"{" +
"\"Version\": \"2012-10-17\"," +
"\"Statement\": [" +
"{" +
"\"Sid\": \"\"," +
"\"Effect\": \"Allow\"," +
"\"Principal\": {" +
"\"Service\": \"lambda.amazonaws.com\"" +
"}," +
"\"Action\": \"sts:AssumeRole\"" +
"}" +
"]" +
"}";
private Role createdRole;
public CreateBasicLambdaRoleDialog(Shell parentShell, AwsResourceScopeParamBase param) {
super(
parentShell,
"Create Role",
"Create a basic IAM role that allows Lambda Function to call AWS services on your behalf.",
"Creating the Role...",
"Role Name:",
"lambda_basic_execution");
this.param = param;
}
@Override
protected void performFinish(String input) {
AmazonIdentityManagement iam = AwsToolkitCore.getClientFactory(param.getAccountId())
.getIAMClient();
CreateRoleResult result = iam.createRole(new CreateRoleRequest()
.withRoleName(input)
.withAssumeRolePolicyDocument(ASSUME_ROLE_POLICY));
createdRole = result.getRole();
String policyArn = iam.createPolicy(
new CreatePolicyRequest()
.withPolicyName(getRandomPolicyName())
.withPolicyDocument(BASIC_ROLE_POLICY)
).getPolicy().getArn();
iam.attachRolePolicy(new AttachRolePolicyRequest()
.withRoleName(input)
.withPolicyArn(policyArn));
// Sleep for 10 seconds so that the policy change can be fully populated
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
setMessage("Role created. Waiting for the attached role policy to be fully available...");
}
});
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private String getRandomPolicyName() {
return "lambda_basic_execution_role_policy_"
+ UUID.randomUUID().toString();
}
@Override
public Role getCreatedResource() {
return createdRole;
}
}
| 7,961 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/model/UploadFunctionWizardDataModel.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.upload.wizard.model;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IJavaElement;
import com.amazonaws.eclipse.core.model.RegionDataModel;
import com.amazonaws.eclipse.core.model.SelectOrCreateBucketDataModel;
import com.amazonaws.eclipse.core.model.SelectOrCreateKmsKeyDataModel;
import com.amazonaws.eclipse.lambda.ServiceApiUtils;
import com.amazonaws.eclipse.lambda.model.SelectOrCreateBasicLambdaRoleDataModel;
import com.amazonaws.eclipse.lambda.model.SelectOrInputFunctionAliasDataModel;
import com.amazonaws.eclipse.lambda.model.SelectOrInputFunctionDataModel;
import com.amazonaws.eclipse.lambda.project.metadata.LambdaFunctionProjectMetadata;
import com.amazonaws.services.lambda.model.CreateFunctionRequest;
import com.amazonaws.services.lambda.model.UpdateFunctionConfigurationRequest;
public class UploadFunctionWizardDataModel {
public static final String P_HANDLER = "handler";
private final IProject project;
private final IJavaElement selectedJavaElement;
private final List<String> requestHandlerImplementerClasses;
private final LambdaFunctionProjectMetadata projectMetadataBeforeUpload;
/* Page 1 */
private String handler;
private final RegionDataModel regionDataModel = new RegionDataModel();
private final SelectOrInputFunctionDataModel functionDataModel = new SelectOrInputFunctionDataModel();
/* Page 2 */
private final SelectOrCreateBasicLambdaRoleDataModel lambdaRoleDataModel = new SelectOrCreateBasicLambdaRoleDataModel();
private final SelectOrInputFunctionAliasDataModel functionAliasDataModel = new SelectOrInputFunctionAliasDataModel();
private final SelectOrCreateBucketDataModel s3BucketDataModel = new SelectOrCreateBucketDataModel();
private final SelectOrCreateKmsKeyDataModel kmsKeyDataModel = new SelectOrCreateKmsKeyDataModel();
private final FunctionConfigPageDataModel functionConfigPageDataModel = new FunctionConfigPageDataModel();;
public CreateFunctionRequest toCreateFunctionRequest() {
return new CreateFunctionRequest()
.withFunctionName(functionDataModel.getFunctionName())
.withRuntime(ServiceApiUtils.JAVA_8)
.withDescription(functionConfigPageDataModel.getDescription())
.withHandler(getHandler())
.withRole(getLambdaRoleDataModel().getExistingResource().getArn())
.withMemorySize(functionConfigPageDataModel.getMemory().intValue())
.withTimeout(functionConfigPageDataModel.getTimeout().intValue())
.withPublish(functionConfigPageDataModel.isPublishNewVersion());
}
public UpdateFunctionConfigurationRequest toUpdateFunctionConfigRequest() {
return new UpdateFunctionConfigurationRequest()
.withFunctionName(functionDataModel.getFunctionName())
.withDescription(functionConfigPageDataModel.getDescription())
.withHandler(getHandler())
.withRole(getLambdaRoleDataModel().getExistingResource().getArn())
.withMemorySize(functionConfigPageDataModel.getMemory().intValue())
.withTimeout(functionConfigPageDataModel.getTimeout().intValue());
}
/**
* @param project
* the project being uploaded
* @param requestHandlerImplementerClasses
* a non-empty list of FQCNs of the classes within the project
* that implement the RequestHandler interface.
* @param projectMetadataBeforeUpload
* the existing persistent metadata for this project
*/
public UploadFunctionWizardDataModel(IProject project,
IJavaElement selectedJavaElement,
List<String> requestHandlerImplementerClasses,
LambdaFunctionProjectMetadata projectMetadataBeforeUpload) {
this.project = project;
this.selectedJavaElement = selectedJavaElement;
this.projectMetadataBeforeUpload = projectMetadataBeforeUpload == null ?
new LambdaFunctionProjectMetadata() : projectMetadataBeforeUpload;
if (requestHandlerImplementerClasses.isEmpty()) {
throw new IllegalArgumentException(
"requestHandlerImplementerClasses must not be empty.");
}
this.requestHandlerImplementerClasses = Collections
.unmodifiableList(requestHandlerImplementerClasses);
}
public IProject getProject() {
return project;
}
public List<String> getRequestHandlerImplementerClasses() {
return requestHandlerImplementerClasses;
}
public LambdaFunctionProjectMetadata getProjectMetadataBeforeUpload() {
return projectMetadataBeforeUpload;
}
public FunctionConfigPageDataModel getFunctionConfigPageDataModel() {
return functionConfigPageDataModel;
}
public String getHandler() {
return handler;
}
public void setHandler(String handler) {
this.handler = handler;
}
public SelectOrCreateBasicLambdaRoleDataModel getLambdaRoleDataModel() {
return lambdaRoleDataModel;
}
public SelectOrInputFunctionAliasDataModel getFunctionAliasDataModel() {
return functionAliasDataModel;
}
public RegionDataModel getRegionDataModel() {
return regionDataModel;
}
public SelectOrInputFunctionDataModel getFunctionDataModel() {
return functionDataModel;
}
public SelectOrCreateBucketDataModel getS3BucketDataModel() {
return s3BucketDataModel;
}
public SelectOrCreateKmsKeyDataModel getKmsKeyDataModel() {
return kmsKeyDataModel;
}
}
| 7,962 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/lambda/upload/wizard/model/FunctionConfigPageDataModel.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.upload.wizard.model;
public class FunctionConfigPageDataModel {
public static final String P_DESCRIPTION = "description";
public static final String P_MEMORY = "memory";
public static final String P_TIMEOUT = "timeout";
public static final String P_PUBLISH_NEW_VERSION = "publishNewVersion";
public static final String P_CREATE_NEW_VERSION_ALIAS = "createNewVersionAlias";
public static final String P_NONE_ENCRYPTION = "noneEncryption";
public static final String P_S3_ENCRYPTION = "s3Encryption";
public static final String P_KMS_ENCRYPTION = "kmsEncryption";
private String description;
private boolean publishNewVersion;
private boolean createNewVersionAlias;
private Long memory;
private Long timeout;
private boolean noneEncryption = true;
private boolean s3Encryption = false;
private boolean kmsEncryption = false;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isPublishNewVersion() {
return publishNewVersion;
}
public void setPublishNewVersion(boolean publishNewVersion) {
this.publishNewVersion = publishNewVersion;
}
public boolean isCreateNewVersionAlias() {
return createNewVersionAlias;
}
public void setCreateNewVersionAlias(boolean createNewVersionAlias) {
this.createNewVersionAlias = createNewVersionAlias;
}
public Long getMemory() {
return memory;
}
public void setMemory(Long memory) {
this.memory = memory;
}
public Long getTimeout() {
return timeout;
}
public void setTimeout(Long timeout) {
this.timeout = timeout;
}
public boolean isNoneEncryption() {
return noneEncryption;
}
public void setNoneEncryption(boolean noneEncryption) {
this.noneEncryption = noneEncryption;
}
public boolean isS3Encryption() {
return s3Encryption;
}
public void setS3Encryption(boolean s3Encryption) {
this.s3Encryption = s3Encryption;
}
public boolean isKmsEncryption() {
return kmsEncryption;
}
public void setKmsEncryption(boolean kmsEncryption) {
this.kmsEncryption = kmsEncryption;
}
}
| 7,963 |
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/blueprint/ServerlessBlueprintsConfig.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.blueprint;
import java.util.Map;
public class ServerlessBlueprintsConfig {
private String version;
private String defaultBlueprint;
private Map<String, ServerlessBlueprint> blueprints;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDefaultBlueprint() {
return defaultBlueprint;
}
public void setDefaultBlueprint(String defaultBlueprint) {
this.defaultBlueprint = defaultBlueprint;
}
public Map<String, ServerlessBlueprint> getBlueprints() {
return blueprints;
}
public void setBlueprints(Map<String, ServerlessBlueprint> blueprints) {
this.blueprints = blueprints;
}
}
| 7,964 |
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/blueprint/BlueprintsProvider.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.blueprint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.amazonaws.eclipse.lambda.project.template.CodeTemplateManager;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Class that parses Serverless and Lambda blueprints config files.
*/
public class BlueprintsProvider {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static volatile ServerlessBlueprintsConfig serverlessBlueprintsConfig;
private static volatile LambdaBlueprintsConfig lambdaBlueprintsConfig;
public static ServerlessBlueprintsConfig provideServerlessBlueprints() {
if (serverlessBlueprintsConfig == null) {
try {
serverlessBlueprintsConfig = MAPPER.readValue(
CodeTemplateManager.getInstance().getServerlessBlueprintsConfigFile(),
ServerlessBlueprintsConfig.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return serverlessBlueprintsConfig;
}
public static List<String> getServerlessBlueprintDisplayNames() {
ServerlessBlueprintsConfig config = provideServerlessBlueprints();
List<String> displayNames = new ArrayList<>();
for (ServerlessBlueprint blueprint : config.getBlueprints().values()) {
displayNames.add(blueprint.getDisplayName());
}
return displayNames;
}
public static LambdaBlueprintsConfig provideLambdaBlueprints() {
if (lambdaBlueprintsConfig == null) {
try {
lambdaBlueprintsConfig = MAPPER.readValue(
CodeTemplateManager.getInstance().getLambdaBlueprintsConfigFile(),
LambdaBlueprintsConfig.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return lambdaBlueprintsConfig;
}
}
| 7,965 |
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/blueprint/ServerlessBlueprint.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.blueprint;
import java.util.Map;
public class ServerlessBlueprint {
private String baseDir;
private String displayName;
private String description;
private Map<String, String> handlerTemplatePaths;
private boolean needLambdaProxyIntegrationModel;
public String getBaseDir() {
return baseDir;
}
public void setBaseDir(String baseDir) {
this.baseDir = baseDir;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Map<String, String> getHandlerTemplatePaths() {
return handlerTemplatePaths;
}
public void setHandlerTemplatePaths(Map<String, String> handlerTemplatePaths) {
this.handlerTemplatePaths = handlerTemplatePaths;
}
public boolean isNeedLambdaProxyIntegrationModel() {
return needLambdaProxyIntegrationModel;
}
public void setNeedLambdaProxyIntegrationModel(
boolean needLambdaProxyIntegrationModel) {
this.needLambdaProxyIntegrationModel = needLambdaProxyIntegrationModel;
}
}
| 7,966 |
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/blueprint/LambdaBlueprintsConfig.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.blueprint;
import java.util.Map;
public class LambdaBlueprintsConfig {
private String version;
private String defaultBlueprint;
private Map<String, LambdaBlueprint> blueprints;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDefaultBlueprint() {
return defaultBlueprint;
}
public void setDefaultBlueprint(String defaultBlueprint) {
this.defaultBlueprint = defaultBlueprint;
}
public Map<String, LambdaBlueprint> getBlueprints() {
return blueprints;
}
public void setBlueprints(Map<String, LambdaBlueprint> blueprints) {
this.blueprints = blueprints;
}
}
| 7,967 |
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/blueprint/LambdaBlueprint.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.blueprint;
import com.amazonaws.eclipse.core.model.ComboBoxItemData;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class LambdaBlueprint implements ComboBoxItemData {
private String baseDir;
private String displayName;
private String description;
private String testJsonFile;
private String testReturnedValue;
public String getBaseDir() {
return baseDir;
}
public void setBaseDir(String baseDir) {
this.baseDir = baseDir;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTestJsonFile() {
return testJsonFile;
}
public void setTestJsonFile(String testJsonFile) {
this.testJsonFile = testJsonFile;
}
public String getTestReturnedValue() {
return testReturnedValue;
}
public void setTestReturnedValue(String testReturnedValue) {
this.testReturnedValue = testReturnedValue;
}
@JsonIgnore
@Override
public String getComboBoxItemLabel() {
return getDisplayName();
}
}
| 7,968 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/org/eclipse/datatools/sqltools/data/internal/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/org/eclipse/datatools/sqltools/data/internal/ui/editor/ITableDataEditor.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 org.eclipse.datatools.sqltools.data.internal.ui.editor;
/*
* This class was introduced in DTP as part of the Eclipse-3.6 Helios release.
* We need to stub it out so that this plugin can work correctly on
* Eclipse-3.5 and Eclipse-3.6.
*/
public class ITableDataEditor {}
| 7,969 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer/simpledb/SimpleDBLabelProvider.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.simpledb;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider;
public class SimpleDBLabelProvider extends ExplorerNodeLabelProvider {
@Override
public String getText(final Object element) {
if ( element instanceof SimpleDBRootElement ) {
return "Amazon SimpleDB";
}
return getExplorerNodeText(element);
}
/**
* Every element in the tree (the root and domains) is represented by a
* table image
*/
@Override
public Image getDefaultImage(final Object element) {
if ( element instanceof SimpleDBRootElement ) {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_SIMPLEDB_SERVICE);
} else {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_TABLE);
}
}
}
| 7,970 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer/simpledb/SimpleDBExplorerNodes.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.simpledb;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.datatools.enablement.simpledb.ui.editor.OpenQueryEditorAction;
import com.amazonaws.eclipse.explorer.ExplorerNode;
public class SimpleDBExplorerNodes {
public static class DomainNode extends ExplorerNode {
public DomainNode(final String domainName) {
super(domainName, 0, loadImage(AwsToolkitCore.IMAGE_TABLE), new OpenQueryEditorAction(domainName));
}
}
private static Image loadImage(final String imageId) {
return AwsToolkitCore.getDefault().getImageRegistry().get(imageId);
}
}
| 7,971 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer/simpledb/SimpleDBContentProvider.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.simpledb;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ITreeContentProvider;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.explorer.AWSResourcesRootElement;
import com.amazonaws.eclipse.explorer.AbstractContentProvider;
import com.amazonaws.eclipse.explorer.Loading;
import com.amazonaws.eclipse.explorer.simpledb.SimpleDBExplorerNodes.DomainNode;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
public class SimpleDBContentProvider extends AbstractContentProvider implements ITreeContentProvider {
private static SimpleDBContentProvider instance;
public SimpleDBContentProvider() {
instance = this;
}
public static SimpleDBContentProvider getInstance() {
return instance;
}
@Override
public boolean hasChildren(final Object element) {
return (element instanceof AWSResourcesRootElement ||
element instanceof SimpleDBRootElement);
}
@Override
public Object[] loadChildren(final Object parentElement) {
if ( parentElement instanceof AWSResourcesRootElement ) {
return new Object[] { SimpleDBRootElement.ROOT_ELEMENT };
}
if ( parentElement instanceof SimpleDBRootElement) {
new DataLoaderThread(parentElement) {
@Override
public Object[] loadData() {
AmazonSimpleDB client = AwsToolkitCore.getClientFactory().getSimpleDBClient();
// Translate the domain names to objects so we can work with them more easily
List<DomainNode> domainNodes = new ArrayList<>();
for (String domainName : client.listDomains().getDomainNames()) {
domainNodes.add(new DomainNode(domainName));
}
return domainNodes.toArray();
}
}.start();
}
return Loading.LOADING;
}
@Override
public String getServiceAbbreviation() {
return ServiceAbbreviations.SIMPLEDB;
}
}
| 7,972 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer/simpledb/OpenSQLScrapbookAction.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.simpledb;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.datatools.connectivity.IConnectionProfile;
import org.eclipse.datatools.sqltools.editor.core.connection.ISQLEditorConnectionInfo;
import org.eclipse.datatools.sqltools.internal.sqlscrapbook.editor.SQLScrapbookEditor;
import org.eclipse.datatools.sqltools.internal.sqlscrapbook.util.SQLFileUtil;
import org.eclipse.datatools.sqltools.sqlbuilder.model.SQLBuilderConnectionInfo;
import org.eclipse.datatools.sqltools.sqleditor.SQLEditorStorageEditorInput;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
public class OpenSQLScrapbookAction extends Action {
public OpenSQLScrapbookAction() {
setText("Open DTP SQL Scrapbook");
setToolTipText("Opens the DTP SQL Scrapbook to run queries on your data");
}
@Override
public void run() {
Region currentRegion = RegionUtils.getCurrentRegion();
String endpoint = currentRegion.getServiceEndpoints().get(ServiceAbbreviations.SIMPLEDB);
if (endpoint.contains("://")) {
endpoint = endpoint.substring(endpoint.indexOf("://") + 3);
}
if (endpoint.endsWith("/")) {
endpoint = endpoint.substring(0, endpoint.lastIndexOf("/"));
}
SimpleDBConnectionProfileManager sdbConnectionProfileManager = new SimpleDBConnectionProfileManager();
IConnectionProfile connectionProfile = sdbConnectionProfileManager.findOrCreateConnectionProfile(endpoint);
IStatus status = connectionProfile.connect();
if (!status.isOK()) {
throw new RuntimeException("Unable to connect to Amazon SimpleDB: " + status.getMessage());
}
ISQLEditorConnectionInfo editorConnectionInfo = new SQLBuilderConnectionInfo(connectionProfile);
SQLEditorStorageEditorInput editorStorageEditorInput = new SQLEditorStorageEditorInput("", "");
editorStorageEditorInput.setConnectionInfo(SQLFileUtil.getConnectionInfo4Scrapbook(editorConnectionInfo));
// the name will show as the title of the editor
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IEditorReference[] editors = window.getActivePage().getEditorReferences();
int suffix = 0;
List<String> editorNameList = new ArrayList<>();
for (int i = 0; i < editors.length; i++) {
editorNameList.add(editors[i].getName());
}
while (true) {
String name = "SQL Scrapbook - " + connectionProfile.getName();
if (suffix > 0) {
name = name + " " + suffix;
}
if (!editorNameList.contains(name)) {
editorStorageEditorInput.setName(name);
try {
window.getActivePage().openEditor(editorStorageEditorInput, SQLScrapbookEditor.EDITOR_ID);
} catch (PartInitException e) {
throw new RuntimeException(e.getMessage(), e);
}
break;
}
suffix++;
}
}
}
| 7,973 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer/simpledb/SimpleDBConnectionProfileManager.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.simpledb;
import java.util.Properties;
import org.eclipse.datatools.connectivity.ConnectionProfileException;
import org.eclipse.datatools.connectivity.IConnectionProfile;
import org.eclipse.datatools.connectivity.ProfileManager;
import org.eclipse.datatools.connectivity.drivers.DriverInstance;
import org.eclipse.datatools.connectivity.drivers.DriverManager;
import org.eclipse.datatools.connectivity.drivers.jdbc.IJDBCConnectionProfileConstants;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.datatools.enablement.simpledb.connection.ISimpleDBConnectionProfileConstants;
public class SimpleDBConnectionProfileManager {
public IConnectionProfile findOrCreateConnectionProfile(final String endpoint) {
// Attempt to use an existing ConnectionProfile
for (IConnectionProfile profile : ProfileManager.getInstance().getProfileByProviderID(ISimpleDBConnectionProfileConstants.SIMPLEDB_PROFILE_PROVIDER_ID)) {
Properties baseProperties = profile.getBaseProperties();
// Ignore any connection profiles that have their AWS security credentials directly
// included in their properties.
String username = baseProperties.getProperty(IJDBCConnectionProfileConstants.USERNAME_PROP_ID);
if (username != null && username.length() > 0) {
continue;
}
boolean isCorrectRegion = endpoint.equals(baseProperties.getProperty(ISimpleDBConnectionProfileConstants.ENDPOINT));
boolean isCorrectAccount = AwsToolkitCore.getDefault().getCurrentAccountId().equals(baseProperties.getProperty(ISimpleDBConnectionProfileConstants.ACCOUNT_ID));
if (isCorrectRegion && isCorrectAccount) {
return profile;
}
}
// If we didn't find a suitable existing ConnectionProfile, create a new one...
DriverInstance driverInstance = DriverManager.getInstance().getDriverInstanceByID(ISimpleDBConnectionProfileConstants.SIMPLEDB_DRIVER_ID);
Properties baseProperties = (Properties)driverInstance.getPropertySet().getBaseProperties().clone();
baseProperties.setProperty(ISimpleDBConnectionProfileConstants.ACCOUNT_ID, AwsToolkitCore.getDefault().getCurrentAccountId());
baseProperties.setProperty(ISimpleDBConnectionProfileConstants.ENDPOINT, endpoint);
try {
String name = createUniqueConnectionProfileName(endpoint);
String description = "Connection to Amazon SimpleDB (" + endpoint + ")";
return ProfileManager.getInstance().createProfile(name, description, ISimpleDBConnectionProfileConstants.SIMPLEDB_PROFILE_PROVIDER_ID, baseProperties);
} catch (ConnectionProfileException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private String createUniqueConnectionProfileName(final String endpoint) {
String currentAccountId = AwsToolkitCore.getDefault().getCurrentAccountId();
String currentAccountName = AwsToolkitCore.getDefault().getAccountManager().getAllAccountNames().get(currentAccountId);
String name;
int suffix = 0;
do {
name = "Amazon SimpleDB (account: " + currentAccountName + ", endpoint: " + endpoint + ")";
if (suffix++ > 0) {
name += " " + suffix;
}
} while (ProfileManager.getInstance().getProfileByName(name) != null);
return name;
}
}
| 7,974 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer/simpledb/OpenDataTableEditorAction.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.simpledb;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.datatools.connectivity.IConnectionProfile;
import org.eclipse.datatools.connectivity.IManagedConnection;
import org.eclipse.datatools.connectivity.sqm.core.connection.ConnectionInfo;
import org.eclipse.datatools.connectivity.sqm.core.rte.jdbc.JDBCSchema;
import org.eclipse.datatools.connectivity.sqm.core.rte.jdbc.JDBCTable;
import org.eclipse.datatools.modelbase.sql.schema.Catalog;
import org.eclipse.datatools.modelbase.sql.schema.Database;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataEditorInput;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
public class OpenDataTableEditorAction extends Action {
private static final String TABLE_DATA_EDITOR_ID = "org.eclipse.datatools.sqltools.data.internal.ui.editor.tableDataEditor";
private final String domainName;
public OpenDataTableEditorAction(final String domainName) {
this.domainName = domainName;
setText("Open DTP Data Editor");
setToolTipText("Opens the DTP data editor for the contents of this domain");
}
private JDBCTable findTableByName(final List<JDBCTable> tables, final String name) {
for (JDBCTable table : tables) {
if (table.getName().equals(this.domainName)) {
return table;
}
}
return null;
}
@Override
public void run() {
Region currentRegion = RegionUtils.getCurrentRegion();
String endpoint = currentRegion.getServiceEndpoints().get(ServiceAbbreviations.SIMPLEDB);
if (endpoint.contains("://")) {
endpoint = endpoint.substring(endpoint.indexOf("://") + 3);
}
if (endpoint.endsWith("/")) {
endpoint = endpoint.substring(0, endpoint.lastIndexOf("/"));
}
SimpleDBConnectionProfileManager sdbConnectionProfileManager = new SimpleDBConnectionProfileManager();
IConnectionProfile connectionProfile = sdbConnectionProfileManager.findOrCreateConnectionProfile(endpoint);
IStatus status = connectionProfile.connect();
if (!status.isOK()) {
throw new RuntimeException("Unable to connect to Amazon SimpleDB: " + status.getMessage());
}
IManagedConnection managedConnection = (connectionProfile).getManagedConnection("org.eclipse.datatools.connectivity.sqm.core.connection.ConnectionInfo");
if (managedConnection != null) {
try {
ConnectionInfo connectionInfo = (ConnectionInfo) managedConnection.getConnection().getRawConnection();
if (connectionInfo != null) {
Database database = connectionInfo.getSharedDatabase();
System.out.println("Schemas:");
int i = 1;
for (Object obj : database.getSchemas()) {
System.out.println(i++ + " - " + obj);
}
// TODO: which catalog?
for (Object obj : database.getCatalogs()) {
Catalog catalog = (Catalog)obj;
EList<JDBCSchema> schemas = catalog.getSchemas();
// TODO: Is this always the right schema?
JDBCSchema schema = schemas.get(0);
EList<JDBCTable> tables = schema.getTables();
JDBCTable table = findTableByName(tables, this.domainName);
if (table != null) {
IWorkbenchPage workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
workbenchPage.openEditor(new TableDataEditorInput(table), TABLE_DATA_EDITOR_ID);
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
| 7,975 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer/simpledb/SimpleDBNavigatorActionProvider.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.simpledb;
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.IStructuredSelection;
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;
import org.eclipse.ui.navigator.CommonActionProvider;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.ContentProviderRegistry;
import com.amazonaws.eclipse.explorer.simpledb.SimpleDBExplorerNodes.DomainNode;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.model.CreateDomainRequest;
import com.amazonaws.services.simpledb.model.DeleteDomainRequest;
import com.amazonaws.services.simpledb.model.DomainMetadataRequest;
import com.amazonaws.services.simpledb.model.DomainMetadataResult;
public class SimpleDBNavigatorActionProvider extends CommonActionProvider {
@Override
public void fillContextMenu(final IMenuManager menu) {
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
if (selection.getFirstElement() == SimpleDBRootElement.ROOT_ELEMENT) {
menu.add(new CreateDomainAction());
} else if (selection.getFirstElement() instanceof DomainNode) {
List<String> domainNames = new ArrayList<>();
Iterator iterator = selection.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
if (next instanceof DomainNode) {
DomainNode domainNode = (DomainNode)next;
domainNames.add(domainNode.getName());
}
}
menu.add(new CreateDomainAction());
menu.add(new DeleteDomainAction(domainNames));
menu.add(new Separator());
menu.add(new OpenSQLScrapbookAction());
DomainNode domainNode = (DomainNode)selection.getFirstElement();
menu.add(new OpenDataTableEditorAction(domainNode.getName()));
menu.add(new Separator());
menu.add(new ShowDomainMetadataAction(domainNode.getName()));
}
}
private static class ShowDomainMetadataAction extends Action {
private final String domain;
public ShowDomainMetadataAction(final String domain) {
this.setText("View domain metadata");
this.setToolTipText("View metadata for this domain");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_ICON));
this.setAccelerator(SWT.ALT | findKeyCode("ENTER"));
this.domain = domain;
}
@Override
public void run() {
new DomainMetadataDialog().open();
}
class DomainMetadataDialog extends MessageDialog {
protected DomainMetadataDialog() {
super(Display.getDefault().getActiveShell(), "Domain Metadata", AwsToolkitCore.getDefault()
.getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON),
"Domain Metadata for " + ShowDomainMetadataAction.this.domain, MessageDialog.NONE, new String[] { "OK" }, 0);
}
@Override
protected Control createDialogArea(final Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(2, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
composite.setLayout(layout);
GridData data = new GridData(GridData.FILL_BOTH);
data.horizontalSpan = 2;
composite.setLayoutData(data);
Label title = new Label(composite, SWT.None);
title.setText("Domain Metadata for " + ShowDomainMetadataAction.this.domain);
title.setLayoutData(data);
DomainMetadataResult domainMetadata = AwsToolkitCore.getClientFactory().getSimpleDBClient()
.domainMetadata(new DomainMetadataRequest().withDomainName(ShowDomainMetadataAction.this.domain));
new Label(composite, SWT.NONE).setText("Item count: ");
new Label(composite, SWT.NONE).setText("" + domainMetadata.getItemCount());
new Label(composite, SWT.READ_ONLY).setText("Total item name size (bytes): ");
new Label(composite, SWT.READ_ONLY).setText("" + domainMetadata.getItemNamesSizeBytes());
new Label(composite, SWT.READ_ONLY).setText("Distinct attribute names: ");
new Label(composite, SWT.READ_ONLY).setText("" + domainMetadata.getAttributeNameCount());
new Label(composite, SWT.READ_ONLY).setText("Total attribute name size (bytes): ");
new Label(composite, SWT.READ_ONLY).setText("" + domainMetadata.getAttributeNamesSizeBytes());
new Label(composite, SWT.READ_ONLY).setText("Name / value pairs: ");
new Label(composite, SWT.READ_ONLY).setText("" + domainMetadata.getAttributeValueCount());
new Label(composite, SWT.READ_ONLY).setText("Total name / value pair size (bytes): ");
new Label(composite, SWT.READ_ONLY).setText("" + domainMetadata.getAttributeValuesSizeBytes());
return composite;
}
}
}
private static class CreateDomainAction extends Action {
public CreateDomainAction() {
this.setText("Create New Domain");
this.setToolTipText("Create a new Amazon SimpleDB domain");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD));
}
@Override
public void run() {
CreateDomainDialog createDomainDialog = new CreateDomainDialog();
if (createDomainDialog.open() != 0) {
return;
}
try {
AmazonSimpleDB sdb = AwsToolkitCore.getClientFactory().getSimpleDBClient();
sdb.createDomain(new CreateDomainRequest(createDomainDialog.getDomainName()));
ContentProviderRegistry.refreshAllContentProviders();
} catch (Exception e) {
AwsToolkitCore.getDefault().reportException("Unable to create domain '" + createDomainDialog.getDomainName() + "'", e);
}
}
private class CreateDomainDialog extends MessageDialog {
private String domainName;
public CreateDomainDialog() {
super(Display.getDefault().getActiveShell(),
"Create New SimpleDB Domain", null, "Enter the name for your new SimpleDB domain.",
MessageDialog.INFORMATION, new String[] {"OK", "Cancel"}, 0);
}
public String getDomainName() {
return this.domainName;
}
@Override
protected Control createCustomArea(final 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("Domain Name:");
final Text domainNameText = new Text(composite, SWT.BORDER);
domainNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
domainNameText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(final ModifyEvent e) {
CreateDomainDialog.this.domainName = domainNameText.getText();
updateControls();
}
});
return composite;
}
private void updateControls() {
boolean isValid = (this.domainName != null && this.domainName.length() > 0);
Button okButton = this.getButton(0);
if (okButton != null) {
okButton.setEnabled(isValid);
}
}
@Override
protected void createButtonsForButtonBar(final Composite parent) {
super.createButtonsForButtonBar(parent);
updateControls();
}
}
}
private static class DeleteDomainAction extends Action {
private final List<String> domainNames;
public DeleteDomainAction(final List<String> domainNames) {
this.domainNames = domainNames;
this.setText("Delete Domain" + (domainNames.size() > 1 ? "s" : ""));
this.setToolTipText("Delete the selected Amazon SimpleDB domains");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE));
}
@Override
public void run() {
Dialog dialog = newConfirmationDialog("Delete selected domains?", "Are you sure you want to delete the selected Amazon SimpleDB domains?");
if (dialog.open() != 0) {
return;
}
AmazonSimpleDB simpleDB = new AwsToolkitCore().getClientFactory().getSimpleDBClient();
for (String domainName : this.domainNames) {
try {
simpleDB.deleteDomain(new DeleteDomainRequest(domainName));
} catch (Exception e) {
AwsToolkitCore.getDefault().logError("Unable to delete domain '" + domainName + "'", e);
}
}
ContentProviderRegistry.refreshAllContentProviders();
}
private Dialog newConfirmationDialog(final String title, final String message) {
return new MessageDialog(Display.getDefault().getActiveShell(), title, null, message, MessageDialog.WARNING, new String[] {"OK", "Cancel"}, 0);
}
}
}
| 7,976 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/explorer/simpledb/SimpleDBRootElement.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.simpledb;
import org.eclipse.core.runtime.PlatformObject;
/**
* Root element for SDB domains in the resource browser
*/
public class SimpleDBRootElement extends PlatformObject {
public static SimpleDBRootElement ROOT_ELEMENT = new SimpleDBRootElement();
private SimpleDBRootElement() {
}
}
| 7,977 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/Messages.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui;
import org.eclipse.osgi.util.NLS;
public class Messages {
private static final String BUNDLE_NAME = "com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.messages"; //$NON-NLS-1$
public static String domainDeleteMenu;
public static String EditorsToBeClosed;
public static String EditorsToBeClosedMessage;
public static String ConfirmAttributeDeletion;
public static String ConfirmAttributeDeletionMessage;
public static String ConfirmDomainDeletion;
public static String ConfirmDomainDeletionDescription;
public static String CreateNewDomain;
public static String NewDomainName;
public static String EmptyDomainName;
public static String InvalidDomainName;
public static String InvalidDomainNameDescription;
public static String CreateNewAttribute;
public static String NewAttributeName;
public static String EmptyAttributeName;
public static String attributeDeleteMenu;
public static String GENERATE_DDL_MENU_TEXT;
public static String loadDataMenu;
public static String attributeNewMenu;
public static String domainNewMenu;
private Messages() {
}
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
}
| 7,978 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/expressions/SQLNodePropertyTester.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.expressions;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.datatools.connectivity.sqm.core.ui.explorer.virtual.IVirtualNode;
import org.eclipse.datatools.modelbase.sql.schema.Catalog;
import org.eclipse.datatools.modelbase.sql.schema.Database;
import org.eclipse.datatools.modelbase.sql.schema.Schema;
import org.eclipse.datatools.modelbase.sql.tables.Column;
import org.eclipse.datatools.modelbase.sql.tables.Table;
public class SQLNodePropertyTester extends PropertyTester {
@Override
public boolean test(final Object receiver, final String property, final Object[] args, final Object expectedValue) {
if (!"vendor".equalsIgnoreCase(property)) { //$NON-NLS-1$
return false;
}
if (receiver instanceof IVirtualNode) {
IVirtualNode node = (IVirtualNode) receiver;
Database db = node.getParentConnection().getSharedDatabase();
return expectedValue.toString().equalsIgnoreCase(db.getVendor());
}
if (receiver instanceof Table) {
Table table = (Table) receiver;
Database db = table.getSchema().getDatabase() == null ? table.getSchema().getCatalog().getDatabase() : table
.getSchema().getDatabase();
return expectedValue.toString().equalsIgnoreCase(db.getVendor());
}
if (receiver instanceof Column) {
Column column = (Column) receiver;
Schema schema = column.getTable().getSchema();
Database db = schema.getDatabase() == null ? schema.getCatalog().getDatabase() : schema.getDatabase();
return expectedValue.toString().equalsIgnoreCase(db.getVendor());
}
if (receiver instanceof Catalog) {
Catalog catalog = (Catalog) receiver;
Database db = catalog.getDatabase();
return expectedValue.toString().equalsIgnoreCase(db.getVendor());
}
if (receiver instanceof Schema) {
Schema schema = (Schema) receiver;
Database db = schema.getDatabase() == null ? schema.getCatalog().getDatabase() : schema.getDatabase();
return expectedValue.toString().equalsIgnoreCase(db.getVendor());
}
if (receiver instanceof Database) {
Database db = (Database) receiver;
return expectedValue.toString().equalsIgnoreCase(db.getVendor());
}
return false;
}
}
| 7,979 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/DeleteAttributeActionProvider.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.AbstractAction;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.providers.AbstractActionProvider;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.SelectionChangedEvent;
public class DeleteAttributeActionProvider extends AbstractActionProvider {
private static final AbstractAction action = new DeleteAttributeWizardAction();
@Override
protected AbstractAction getAction() {
return action;
}
@Override
public void fillContextMenu(final IMenuManager menu) {
getAction().setCommonViewer(this.viewer);
getAction().selectionChanged(new SelectionChangedEvent(this.selectionProvider, this.getContext().getSelection()));
menu.add(action);
}
}
| 7,980 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/NewAttributeActionProvider.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.AbstractAction;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.providers.AbstractActionProvider;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.SelectionChangedEvent;
public class NewAttributeActionProvider extends AbstractActionProvider {
private static final AbstractAction action = new NewAttributeWizardAction();
@Override
protected AbstractAction getAction() {
return action;
}
@Override
public void fillContextMenu(final IMenuManager menu) {
getAction().setCommonViewer(this.viewer);
getAction().selectionChanged(new SelectionChangedEvent(this.selectionProvider, this.getContext().getSelection()));
menu.add(action);
}
}
| 7,981 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/LoadDataAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.AbstractAction;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.Messages;
public class LoadDataAction extends AbstractAction {
private static final String TEXT = Messages.loadDataMenu;
protected Table table = null;
@Override
protected void initialize() {
initializeAction(null, null, TEXT, TEXT);
}
@Override
public void run() {
}
@Override
public void selectionChanged(final SelectionChangedEvent event) {
this.table = null;
if (event.getSelection() instanceof IStructuredSelection) {
if (((IStructuredSelection) event.getSelection()).getFirstElement() instanceof Table) {
this.table = (Table) ((IStructuredSelection) event.getSelection()).getFirstElement();
}
}
if (isEnabled() && this.table != null) {
}
setEnabled(false);
}
}
| 7,982 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/DeleteDomainWizardAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import java.sql.Connection;
import java.text.MessageFormat;
import java.util.Iterator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.datatools.connectivity.sqm.core.connection.DatabaseConnectionRegistry;
import org.eclipse.datatools.connectivity.sqm.core.containment.ContainmentService;
import org.eclipse.datatools.connectivity.sqm.core.rte.ICatalogObject;
import org.eclipse.datatools.connectivity.sqm.internal.core.RDBCorePlugin;
import org.eclipse.datatools.connectivity.sqm.internal.core.connection.ConnectionInfo;
import org.eclipse.datatools.connectivity.sqm.internal.core.containment.GroupID;
import org.eclipse.datatools.modelbase.sql.schema.Database;
import org.eclipse.datatools.modelbase.sql.schema.Schema;
import org.eclipse.datatools.modelbase.sql.tables.PersistentTable;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.navigator.CommonViewer;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.eclipse.datatools.enablement.simpledb.internal.driver.JdbcStatement;
import com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.Messages;
public class DeleteDomainWizardAction extends AbstractEditorClosingAction {
private static final String TEXT = Messages.domainDeleteMenu;
@Override
public void selectionChanged(final SelectionChangedEvent event) {
super.selectionChanged(event);
if (event.getSelection() instanceof IStructuredSelection
&& ((IStructuredSelection) event.getSelection()).getFirstElement() instanceof EObject) {
EObject o = (EObject) ((IStructuredSelection) event.getSelection()).getFirstElement();
ContainmentService containmentService = RDBCorePlugin.getDefault().getContainmentService();
String groupID = containmentService.getGroupId(o);
setEnabled((groupID != null) && (groupID.startsWith(GroupID.CORE_PREFIX)));
}
}
@Override
public void initialize() {
initializeAction(null, null, TEXT, TEXT);
}
@Override
public void run() {
if (!this.event.getSelection().isEmpty()) {
Iterator<?> iter = ((IStructuredSelection) this.event.getSelection()).iterator();
Object selectedObj = iter.next();
if (selectedObj instanceof PersistentTable) {
boolean confirmed = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(),
Messages.ConfirmDomainDeletion, MessageFormat.format(Messages.ConfirmDomainDeletionDescription,
((Table) selectedObj).getName()));
if (!confirmed) {
return;
}
if (!closeEditors((Table) selectedObj)) {
return;
}
Database db = getDatabase(((PersistentTable) selectedObj).getSchema());
ConnectionInfo conInfo = (ConnectionInfo) DatabaseConnectionRegistry.getConnectionForDatabase(db);
final PersistentTable table = (PersistentTable) selectedObj;
try {
deleteTable(conInfo, table);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
private Database getDatabase(final Schema schema) {
return schema.getCatalog() == null ? schema.getDatabase() : schema.getCatalog().getDatabase();
}
/**
* @param profile
* @param table
*/
private void deleteTable(final ConnectionInfo info, final PersistentTable table) throws Exception {
final Database db = table.getSchema().getDatabase() != null ? table.getSchema().getDatabase() : table.getSchema()
.getCatalog().getDatabase();
// final DatabaseDefinition databaseDefinition = RDBCorePlugin.getDefault().getDatabaseDefinitionRegistry()
// .getDefinition(db);
WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
@Override
protected void execute(final IProgressMonitor monitor) {
try {
// SQLDevToolsConfiguration f = SQLToolsFacade.getConfigurationByProfileName(info.getConnectionProfile().getName());
// ConnectionService conService = f.getConnectionService();
// DatabaseIdentifier databaseIdentifier = new DatabaseIdentifier(info.getConnectionProfile().getName(), info.getDatabaseName());
//Connection conn = conService.createConnection(databaseIdentifier, true);
// String profileName = profile.getName();
// DatabaseVendorDefinitionId dbVendorId = ProfileUtil.getDatabaseVendorDefinitionId(profileName);
// ISQLEditorConnectionInfo ci = new SQLEditorConnectionInfo(dbVendorId, profileName, db.getName());
Connection conn = info.getSharedConnection();
conn.prepareStatement("delete domain " + JdbcStatement.DELIMITED_IDENTIFIER_QUOTE + table.getName() //$NON-NLS-1$
+ JdbcStatement.DELIMITED_IDENTIFIER_QUOTE).executeUpdate();
CommonViewer cViewer = (CommonViewer) DeleteDomainWizardAction.this.event.getSource();
TreePath[] expanded = cViewer.getExpandedTreePaths();
// Object selected = ((IStructuredSelection) DeleteDomainWizardAction.this.event.getSelection())
// .getFirstElement();
((ICatalogObject) db).refresh();
for (TreePath path : expanded) {
cViewer.expandToLevel(path, 0);
}
cViewer.setSelection(new StructuredSelection(db), true);
} catch (Exception e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} finally {
monitor.done();
}
}
};
Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().run(false, true, operation);
}
}
| 7,983 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/DeleteAttributeWizardAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import java.sql.Connection;
import java.text.MessageFormat;
import java.util.Iterator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.datatools.connectivity.sqm.core.connection.DatabaseConnectionRegistry;
import org.eclipse.datatools.connectivity.sqm.core.containment.ContainmentService;
import org.eclipse.datatools.connectivity.sqm.core.rte.ICatalogObject;
import org.eclipse.datatools.connectivity.sqm.internal.core.RDBCorePlugin;
import org.eclipse.datatools.connectivity.sqm.internal.core.connection.ConnectionInfo;
import org.eclipse.datatools.connectivity.sqm.internal.core.containment.GroupID;
import org.eclipse.datatools.modelbase.sql.schema.Database;
import org.eclipse.datatools.modelbase.sql.schema.Schema;
import org.eclipse.datatools.modelbase.sql.tables.Column;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.navigator.CommonViewer;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.eclipse.datatools.enablement.simpledb.internal.driver.JdbcStatement;
import com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.Messages;
public class DeleteAttributeWizardAction extends AbstractEditorClosingAction {
private static final String TEXT = Messages.attributeDeleteMenu;
@Override
public void selectionChanged(final SelectionChangedEvent event) {
super.selectionChanged(event);
if (event.getSelection() instanceof IStructuredSelection
&& ((IStructuredSelection) event.getSelection()).getFirstElement() instanceof EObject) {
EObject o = (EObject) ((IStructuredSelection) event.getSelection()).getFirstElement();
ContainmentService containmentService = RDBCorePlugin.getDefault().getContainmentService();
String groupID = containmentService.getGroupId(o);
setEnabled((groupID != null) && (groupID.startsWith(GroupID.CORE_PREFIX)));
}
}
@Override
public void initialize() {
initializeAction(null, null, TEXT, TEXT);
}
@Override
public void run() {
if (!this.event.getSelection().isEmpty()) {
Iterator<?> iter = ((IStructuredSelection) this.event.getSelection()).iterator();
Object selectedObj = iter.next();
if (selectedObj instanceof Column) {
Column column = (Column) selectedObj;
boolean confirmed = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(),
Messages.ConfirmAttributeDeletion, MessageFormat.format(Messages.ConfirmAttributeDeletionMessage, column
.getTable().getName()
+ "." + column.getName())); //$NON-NLS-1$
if (!confirmed) {
return;
}
if (!closeEditors(column.getTable())) {
return;
}
Database db = getDatabase(column.getTable().getSchema());
ConnectionInfo conInfo = (ConnectionInfo) DatabaseConnectionRegistry.getConnectionForDatabase(db);
try {
deleteColumn(conInfo, column);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
private Database getDatabase(final Schema schema) {
return schema.getCatalog() == null ? schema.getDatabase() : schema.getCatalog().getDatabase();
}
/**
* @param info
* @param column
*/
private void deleteColumn(final ConnectionInfo info, final Column column) throws Exception {
final Table table = column.getTable();
WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
@Override
protected void execute(final IProgressMonitor monitor) {
try {
Connection conn = info.getSharedConnection();
conn.prepareStatement("alter table " + JdbcStatement.DELIMITED_IDENTIFIER_QUOTE + table.getName() //$NON-NLS-1$
+ JdbcStatement.DELIMITED_IDENTIFIER_QUOTE + " drop " + JdbcStatement.DELIMITED_IDENTIFIER_QUOTE //$NON-NLS-1$
+ column.getName() + JdbcStatement.DELIMITED_IDENTIFIER_QUOTE).executeUpdate();
CommonViewer cViewer = (CommonViewer) DeleteAttributeWizardAction.this.event.getSource();
TreePath[] expanded = cViewer.getExpandedTreePaths();
((ICatalogObject) table).refresh();
for (TreePath path : expanded) {
cViewer.expandToLevel(path, 0);
}
cViewer.setSelection(new StructuredSelection(table), true);
} catch (Exception e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} finally {
monitor.done();
}
}
};
Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().run(false, true, operation);
}
}
| 7,984 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/ForwardEngineerActionProvider.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
public class ForwardEngineerActionProvider extends CommonActionProvider {
private static final ForwardEngineerAction action = new ForwardEngineerAction();
protected ISelectionProvider selectionProvider;
protected CommonViewer viewer;
protected ActionContributionItem ITEM;
@Override
public void init(final ICommonActionExtensionSite aSite) {
super.init(aSite);
this.selectionProvider = aSite.getViewSite().getSelectionProvider();
this.viewer = (CommonViewer) aSite.getStructuredViewer();
initActionContributionItem();
}
@Override
public void fillContextMenu(final IMenuManager menu) {
action.setCommonViewer(this.viewer);
action.selectionChanged(new SelectionChangedEvent(this.selectionProvider, this.getContext().getSelection()));
menu.insertAfter("slot3", action); //$NON-NLS-1$
}
protected void initActionContributionItem() {
this.ITEM = new ActionContributionItem(action);
}
}
| 7,985 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/DeleteDomainActionProvider.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.AbstractAction;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.providers.AbstractActionProvider;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.SelectionChangedEvent;
public class DeleteDomainActionProvider extends AbstractActionProvider {
private static final AbstractAction action = new DeleteDomainWizardAction();
@Override
protected AbstractAction getAction() {
return action;
}
@Override
public void fillContextMenu(final IMenuManager menu) {
getAction().setCommonViewer(this.viewer);
getAction().selectionChanged(new SelectionChangedEvent(this.selectionProvider, this.getContext().getSelection()));
menu.add(action);
}
}
| 7,986 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/NewDomainWizardAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import java.sql.Connection;
import java.util.regex.Pattern;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.datatools.connectivity.sqm.core.connection.ConnectionInfo;
import org.eclipse.datatools.connectivity.sqm.core.containment.ContainmentService;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.AbstractAction;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.virtual.ITableNode;
import org.eclipse.datatools.connectivity.sqm.core.rte.ICatalogObject;
import org.eclipse.datatools.connectivity.sqm.internal.core.RDBCorePlugin;
import org.eclipse.datatools.connectivity.sqm.internal.core.containment.GroupID;
import org.eclipse.datatools.connectivity.sqm.internal.core.util.ConnectionUtil;
import org.eclipse.datatools.modelbase.sql.schema.Database;
import org.eclipse.datatools.modelbase.sql.schema.Schema;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.eclipse.datatools.enablement.simpledb.internal.driver.JdbcStatement;
import com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.Messages;
public class NewDomainWizardAction extends AbstractAction {
private static final String TEXT = Messages.domainNewMenu;
@Override
public void selectionChanged(final SelectionChangedEvent event) {
super.selectionChanged(event);
if (event.getSelection() instanceof IStructuredSelection
&& ((IStructuredSelection) event.getSelection()).getFirstElement() instanceof EObject) {
EObject o = (EObject) ((IStructuredSelection) event.getSelection()).getFirstElement();
ContainmentService containmentService = RDBCorePlugin.getDefault().getContainmentService();
String groupID = containmentService.getGroupId(o);
setEnabled((groupID != null) && (groupID.startsWith(GroupID.CORE_PREFIX)));
}
}
@Override
public void initialize() {
initializeAction(null, null, TEXT, TEXT);
}
@Override
public void run() {
if (!this.event.getSelection().isEmpty()) {
try {
Display display = Display.getCurrent();
Object o = ((IStructuredSelection) this.event.getSelection()).getFirstElement();
Database db = findDatabase(o);
if (db != null) {
ConnectionInfo info = ConnectionUtil.getConnectionForEObject(db);
if (info != null) {
InputDialog dlg = new InputDialog(display.getActiveShell(), Messages.CreateNewDomain,
Messages.NewDomainName, "", new IInputValidator() { //$NON-NLS-1$
@Override
public String isValid(final String newText) {
return newText != null && newText.trim().length() > 0 ? null : Messages.EmptyDomainName;
}
});
if (dlg.open() == Window.OK) {
String domainName = dlg.getValue();
if (!Pattern.matches("^[\\w\\.-]{3,255}+$", domainName)) { //$NON-NLS-1$
MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.InvalidDomainName,
Messages.InvalidDomainNameDescription);
return;
}
performFinish(info, domainName, db);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private static Database findDatabase(final Object o) {
if (o instanceof ITableNode) {
ITableNode node = (ITableNode) o;
Object parent = node.getParent();
if (parent instanceof Database) {
return (Database) parent;
}
if (parent instanceof Schema) {
return ((Schema) parent).getDatabase() != null ? ((Schema) parent).getDatabase() : ((Schema) parent)
.getCatalog().getDatabase();
}
}
return null;
}
public boolean performFinish(final ConnectionInfo info, final String domainName, final Database db) {
WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
@Override
protected void execute(final IProgressMonitor monitor) {
try {
// SQLDevToolsConfiguration f = SQLToolsFacade.getConfigurationByProfileName(info.getConnectionProfile().getName());
// ConnectionService conService = f.getConnectionService();
// DatabaseVendorDefinitionId dbVendorId = ProfileUtil.getDatabaseVendorDefinitionId(profileName);
// DatabaseIdentifier databaseIdentifier = new DatabaseIdentifier(info.getConnectionProfile().getName(), info.getDatabaseName());
// Connection conn = conService.createConnection(databaseIdentifier, true);
Connection conn = info.getSharedConnection();
conn.prepareStatement("create domain " + JdbcStatement.DELIMITED_IDENTIFIER_QUOTE + domainName //$NON-NLS-1$
+ JdbcStatement.DELIMITED_IDENTIFIER_QUOTE).executeUpdate();
CommonViewer cViewer = (CommonViewer) NewDomainWizardAction.this.event.getSource();
TreePath[] expanded = cViewer.getExpandedTreePaths();
// Object selected = ((IStructuredSelection) NewDomainWizardAction.this.event.getSelection()).getFirstElement();
((ICatalogObject) db).refresh();
for (TreePath path : expanded) {
cViewer.expandToLevel(path, 0);
}
cViewer.setSelection(new StructuredSelection(db), true);
} catch (Exception e) {
Status status = new Status(IStatus.ERROR,
"com.amazonaws.eclipse.datatools.enablement.simpledb",
"Unable to create domain: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW);
e.printStackTrace();
} finally {
if (monitor != null) {
monitor.done();
}
}
}
};
try {
Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().run(false, true, operation);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
| 7,987 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/NewDomainActionProvider.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.AbstractAction;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.providers.AbstractActionProvider;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.SelectionChangedEvent;
public class NewDomainActionProvider extends AbstractActionProvider {
private static final AbstractAction action = new NewDomainWizardAction();
@Override
protected AbstractAction getAction() {
return action;
}
@Override
public void fillContextMenu(final IMenuManager menu) {
getAction().setCommonViewer(this.viewer);
getAction().selectionChanged(new SelectionChangedEvent(this.selectionProvider, this.getContext().getSelection()));
menu.add(action);
}
}
| 7,988 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/NewAttributeWizardAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import java.sql.Connection;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.datatools.connectivity.sqm.core.connection.ConnectionInfo;
import org.eclipse.datatools.connectivity.sqm.core.containment.ContainmentService;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.providers.content.virtual.ColumnNode;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.virtual.IColumnNode;
import org.eclipse.datatools.connectivity.sqm.core.rte.ICatalogObject;
import org.eclipse.datatools.connectivity.sqm.core.ui.explorer.virtual.IVirtualNode;
import org.eclipse.datatools.connectivity.sqm.internal.core.RDBCorePlugin;
import org.eclipse.datatools.connectivity.sqm.internal.core.containment.GroupID;
import org.eclipse.datatools.connectivity.sqm.internal.core.util.ConnectionUtil;
import org.eclipse.datatools.modelbase.sql.schema.Database;
import org.eclipse.datatools.modelbase.sql.schema.Schema;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.navigator.CommonViewer;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.JdbcConnection;
import com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.Messages;
public class NewAttributeWizardAction extends AbstractEditorClosingAction {
private static final String TEXT = Messages.attributeNewMenu;
@Override
public void selectionChanged(final SelectionChangedEvent event) {
super.selectionChanged(event);
if (event.getSelection() instanceof IStructuredSelection
&& ((IStructuredSelection) event.getSelection()).getFirstElement() instanceof EObject) {
EObject o = (EObject) ((IStructuredSelection) event.getSelection()).getFirstElement();
ContainmentService containmentService = RDBCorePlugin.getDefault().getContainmentService();
String groupID = containmentService.getGroupId(o);
setEnabled((groupID != null) && (groupID.startsWith(GroupID.CORE_PREFIX)));
}
}
@Override
public void initialize() {
initializeAction(null, null, TEXT, TEXT);
}
@Override
public void run() {
if (!this.event.getSelection().isEmpty()) {
try {
Display display = Display.getCurrent();
Object o = ((IStructuredSelection) this.event.getSelection()).getFirstElement();
Table table = findTable(o);
Database db = findDatabase(o);
if (table != null && db != null) {
if (!closeEditors(table)) {
return;
}
ConnectionInfo info = ConnectionUtil.getConnectionForEObject(db);
if (info != null) {
InputDialog dlg = new InputDialog(display.getActiveShell(), Messages.CreateNewAttribute,
Messages.NewAttributeName, "", new IInputValidator() { //$NON-NLS-1$
@Override
public String isValid(final String newText) {
return newText != null && newText.trim().length() > 0 ? null : Messages.EmptyAttributeName;
}
});
if (dlg.open() == Window.OK) {
performFinish(info, table.getName(), dlg.getValue(), o);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private Table findTable(final Object o) {
if (o instanceof IColumnNode) {
ColumnNode node = (ColumnNode) o;
Object parent = node.getParent();
if (parent instanceof Table) {
Table table = (Table) parent;
return table;
}
}
return null;
}
private Database findDatabase(final Object o) {
if (o instanceof IColumnNode) {
ColumnNode node = (ColumnNode) o;
Object parent = node.getParent();
if (parent instanceof Table) {
Table table = (Table) parent;
Schema schema = table.getSchema();
Database db = schema.getDatabase() == null ? schema.getCatalog().getDatabase() : schema.getDatabase();
// JDBCColumn o2 = new JDBCColumn();
// o2.setName("FooBarBaz");
// DatabaseDefinition definition = RDBCorePlugin.getDefault().getDatabaseDefinitionRegistry().getDefinition(db);
// PredefinedDataTypeDefinition pdtd = definition.getPredefinedDataTypeDefinition("TEXT");
// PredefinedDataType pdt = definition.getPredefinedDataType(pdtd);
// o2.setDataType(pdt);
// ((JDBCTable) table).getColumns().add(o2);
// node.addChildren(o2);
// CommonViewer cViewer = (CommonViewer) this.event.getSource();
// // cViewer.getControl().setRedraw(false);
// cViewer.add(node, o2);
// // cViewer.getControl().setRedraw(true);
return db;
}
}
return null;
}
public boolean performFinish(final ConnectionInfo info, final String domainName, final String attrName,
final Object node) {
WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
@Override
protected void execute(final IProgressMonitor monitor) {
try {
// SQLDevToolsConfiguration f = SQLToolsFacade.getConfigurationByProfileName(info.getConnectionProfile().getName());
// ConnectionService conService = f.getConnectionService();
// DatabaseVendorDefinitionId dbVendorId = ProfileUtil.getDatabaseVendorDefinitionId(profileName);
// DatabaseIdentifier databaseIdentifier = new DatabaseIdentifier(info.getConnectionProfile().getName(), info.getDatabaseName());
// Connection conn = conService.createConnection(databaseIdentifier, true);
Connection conn = info.getSharedConnection();
// conn.prepareStatement("create domain " + domainName).executeUpdate();
JdbcConnection jdbcConn = (JdbcConnection) conn;
jdbcConn.addPendingColumn(domainName, attrName);
CommonViewer cViewer = (CommonViewer) NewAttributeWizardAction.this.event.getSource();
TreePath[] expanded = cViewer.getExpandedTreePaths();
// Object selected = ((IStructuredSelection) NewAttributeWizardAction.this.event.getSelection())
// .getFirstElement();
IVirtualNode vnode = (IVirtualNode) node;
ICatalogObject table = (ICatalogObject) vnode.getParent();
table.refresh();
// if (NewAttributeWizardAction.this.event.getSelection() instanceof IStructuredSelection
// && ((IStructuredSelection) NewAttributeWizardAction.this.event.getSelection()).getFirstElement() instanceof EObject) {
// EObject o = (EObject) ((IStructuredSelection) NewAttributeWizardAction.this.event.getSelection())
// .getFirstElement();
// cViewer.expandToLevel(o, 1);
// }
// cViewer.refresh();
// Object col = ((JDBCTable) table).getColumns().get(((JDBCTable) table).getColumns().size() - 1);
for (TreePath path : expanded) {
cViewer.expandToLevel(path, 0);
}
cViewer.setSelection(new StructuredSelection(table), true);
// cViewer.reveal(table);
// cViewer.expandToLevel(table, 2);
// cViewer.setSelection(new StructuredSelection(table));
// cViewer.reveal(((IStructuredSelection) NewAttributeWizardAction.this.event.getSelection()).getFirstElement());
// cViewer.expandToLevel(((IStructuredSelection) NewAttributeWizardAction.this.event.getSelection())
// .getFirstElement(), 1);
// cViewer.setSelection(new StructuredSelection(((IStructuredSelection) NewAttributeWizardAction.this.event
// .getSelection()).getFirstElement()));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (monitor != null) {
monitor.done();
}
}
}
};
try {
Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().run(false, true, operation);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
| 7,989 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/AbstractEditorClosingAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.AbstractAction;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataEditor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.Messages;
/**
* Abstract action which is able to close editors of the given table when asked to.
*/
public abstract class AbstractEditorClosingAction extends AbstractAction {
/**
* @param table
* table to be modified
* @return <code>true</code> if no open editors left; i.e. there was no open editors or user confirmed to close
*/
public boolean closeEditors(final Table table) {
IEditorReference ep = getEditor(table);
if (ep != null) {
boolean confirm = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), Messages.EditorsToBeClosed,
Messages.EditorsToBeClosedMessage);
if (!confirm) {
return false;
}
return ep.getEditor(false).getSite().getPage().closeEditors(new IEditorReference[] { ep }, true);
}
return true;
}
/**
* Get the editor that corresponds to the table and return the reference to the editor.
*
* @param table
* @return
*/
private IEditorReference getEditor(final Table table) {
IWorkbenchWindow[] workbenchWindows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (IWorkbenchWindow window : workbenchWindows) {
IWorkbenchPage[] pages = window.getPages();
for (IWorkbenchPage page : pages) {
IEditorReference[] editorReferences = page.getEditorReferences();
for (IEditorReference reference : editorReferences) {
IEditorPart editor = reference.getEditor(false);
if (editor instanceof TableDataEditor && table.equals(((TableDataEditor) editor).getSqlTable())) {
return reference;
}
}
}
}
return null;
}
}
| 7,990 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/ForwardEngineerAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.icons.ImageDescription;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.navigator.CommonViewer;
import com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.Messages;
public class ForwardEngineerAction extends Action {
private static final String TEXT = Messages.GENERATE_DDL_MENU_TEXT;
private static final ImageDescriptor descriptor = ImageDescription.getGenerateCodeDescriptor();
protected SelectionChangedEvent event;
protected CommonViewer viewer;
public ForwardEngineerAction() {
this.setImageDescriptor(descriptor);
this.setDisabledImageDescriptor(descriptor);
this.setText(TEXT);
this.setToolTipText(TEXT);
}
public void setCommonViewer(final CommonViewer viewer) {
this.viewer = viewer;
}
public void selectionChanged(final SelectionChangedEvent event) {
this.event = event;
setEnabled(false);
}
@Override
public void run() {
}
}
| 7,991 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/ExportDBUDataSetAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IActionDelegate;
public class ExportDBUDataSetAction implements IActionDelegate, ISelectionProvider {
// private Shell mParentShell = null;
private Object mSelectedObject = null;
/**
*
*/
public ExportDBUDataSetAction() {
// Display display = Display.getCurrent();
// this.mParentShell = display.getActiveShell();
}
/* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
@Override
public void run(final IAction action) {
}
/* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
*/
@Override
public void selectionChanged(final IAction action, final ISelection selection) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
@Override
public void addSelectionChangedListener(final ISelectionChangedListener listener) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ISelectionProvider#getSelection()
*/
@Override
public ISelection getSelection() {
return new StructuredSelection(this.mSelectedObject);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
@Override
public void removeSelectionChangedListener(final ISelectionChangedListener listener) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection)
*/
@Override
public void setSelection(final ISelection selection) {
}
}
| 7,992 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/tablewizard/simpledb/ui/popup/actions/LoadDataActionProvider.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.tablewizard.simpledb.ui.popup.actions;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.AbstractAction;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.popup.providers.AbstractSubMenuActionProvider;
import org.eclipse.datatools.sqltools.tabledataeditor.actions.providers.DataGroupProvider;
import org.eclipse.jface.action.ActionContributionItem;
public class LoadDataActionProvider extends AbstractSubMenuActionProvider
{
private static final AbstractAction action = new LoadDataAction();
@Override
protected String getSubMenuId()
{
return DataGroupProvider.DATA_MENU_ID;
}
@Override
protected AbstractAction getAction()
{
return action;
}
@Override
protected ActionContributionItem getActionContributionItem()
{
return this.ITEM;
}
}
| 7,993 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/db | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/db/simpledb/SimpleDBService.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.db.simpledb;
import java.util.ArrayList;
import org.eclipse.datatools.sqltools.db.generic.service.GenericSQLService;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
public class SimpleDBService extends GenericSQLService {
/**
* This is a temporary solution until the SimpleDB specific parsers are completed.
*
* @see org.eclipse.datatools.sqltools.core.services.SQLService#splitSQLByTerminatorLine(java.lang.String,
* java.lang.String[])
*/
@Override
public String[] splitSQLByTerminatorLine(final String sql, final String[] terminators) {
IDocument doc = new Document(sql);
ArrayList<String> groups = new ArrayList<>();
//the start position for current group
int index = 0;
int numberOfLines = doc.getNumberOfLines();
try {
for (int i = 0; i < numberOfLines; i++) {
IRegion r = doc.getLineInformation(i);
String line = doc.get(r.getOffset(), r.getLength());
for (int j = 0; j < terminators.length; j++) {
if (line.trim().equalsIgnoreCase(terminators[j])) {
String string = doc.get(index, r.getOffset() - index);
if (string.trim().length() > 0) {
groups.add(string);
}
index = r.getOffset() + doc.getLineLength(i);
break;
}
}
}
if (index < doc.getLength() - 1) {
String string = doc.get(index, doc.getLength() - index);
if (string.trim().length() > 0) {
groups.add(string);
}
}
} catch (Exception e) {
//parse error, simply return
return new String[] { sql };
}
return groups.toArray(new String[groups.size()]);
}
}
| 7,994 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/db | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/db/simpledb/Messages.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.db.simpledb;
import org.eclipse.osgi.util.NLS;
public class Messages {
private static final String BUNDLE_NAME = "com.amazonaws.eclipse.datatools.sqltools.db.simpledb.messages"; //$NON-NLS-1$
public static String SimpleDB;
public static String AmazonSimpleDB;
private Messages() {
}
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
}
| 7,995 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/db | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/sqltools/db/simpledb/SimpleDBConfiguration.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.sqltools.db.simpledb;
import org.eclipse.datatools.sqltools.core.DatabaseVendorDefinitionId;
import org.eclipse.datatools.sqltools.core.services.SQLService;
import org.eclipse.datatools.sqltools.db.generic.GenericDBConfiguration;
public class SimpleDBConfiguration extends GenericDBConfiguration {
private static SimpleDBConfiguration _instance = null;
public static final String[] SERVER_ALIASES = new String[] { Messages.SimpleDB, Messages.AmazonSimpleDB };
// for eclipse to load this class, we must declare it as public
public SimpleDBConfiguration() {
}
public static SimpleDBConfiguration getInstance() {
return _instance;
}
@Override
public SQLService getSQLService() {
return new SimpleDBService();
}
@Override
public boolean recognize(final String product, final String version) {
DatabaseVendorDefinitionId targetid = new DatabaseVendorDefinitionId(product, version);
for (int i = 0; i < SERVER_ALIASES.length; i++) {
DatabaseVendorDefinitionId id = new DatabaseVendorDefinitionId(SERVER_ALIASES[i], getDatabaseVendorDefinitionId()
.getVersion());
if (id.equals(targetid)) {
return true;
}
}
return false;
}
@Override
public String[] getAssociatedConnectionProfileType() {
return new String[] { "com.amazonaws.eclipse.datatools.enablement.simpledb.connectionProfile" }; //$NON-NLS-1$
}
}
| 7,996 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/Activator.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.enablement.simpledb;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
/** The plug-in ID */
public static final String PLUGIN_ID = "com.amazonaws.eclipse.simpledb"; //$NON-NLS-1$
/** The shared instance */
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.core.runtime.Plugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start(final BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(final BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* Helper method for easier error logging.
*
* @param mess
* @param e
* @param severity
*/
public static void logMessage(final String mess, final Exception e, final int severity) {
final Status status = new Status(severity, PLUGIN_ID, 1, "SimpleDB: " + mess, e); //$NON-NLS-1$
getDefault().getLog().log(status);
}
}
| 7,997 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/ui/editor/OpenQueryEditorAction.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.datatools.enablement.simpledb.ui.editor;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* Opens up the custom query editor on a given domain
*/
public class OpenQueryEditorAction extends Action {
private final String domainName;
public OpenQueryEditorAction(final String domainName) {
this.domainName = domainName;
setText("Open Query Editor");
setToolTipText("Opens the query editor to run queries against this domain");
}
@Override
public void run() {
try {
IWorkbenchPage workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
workbenchPage.openEditor(new DomainEditorInput(this.domainName, AwsToolkitCore.getDefault()
.getCurrentAccountId()), QueryEditor.ID);
} catch ( PartInitException e ) {
AwsToolkitCore.getDefault().logError(e.getMessage(), e);
}
}
}
| 7,998 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/ui/editor/SimpleDBItem.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.datatools.enablement.simpledb.ui.editor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.amazonaws.services.simpledb.model.Attribute;
import com.amazonaws.services.simpledb.model.Item;
/**
* Simple container class to collate multi-value fields into a single
* collection.
*/
public class SimpleDBItem {
final String itemName;
final Map<String, Collection<String>> attributes;
final List<String> columns;
public SimpleDBItem(final Item item) {
this.itemName = item.getName();
this.attributes = new TreeMap<>();
this.columns = new ArrayList<>();
String currCol = null;
for ( Attribute att : item.getAttributes() ) {
if ( currCol == null || !currCol.equals(att.getName()) ) {
this.columns.add(att.getName());
}
if ( !this.attributes.containsKey(att.getName()) ) {
this.attributes.put(att.getName(), new LinkedList<String>());
}
this.attributes.get(att.getName()).add(att.getValue());
}
}
}
| 7,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.