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.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/MultiValueAttributeEditorDialog.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.datatools.enablement.simpledb.ui.editor;
import org.eclipse.swt.widgets.Shell;
import com.amazonaws.eclipse.core.ui.MultiValueEditorDialog;
/**
* Simple table dialog to allow use user to enter multiple values for an
* attribute.
*/
class MultiValueAttributeEditorDialog extends MultiValueEditorDialog {
private final SimpleDBItem item;
private final String attributeName;
public MultiValueAttributeEditorDialog(final Shell parentShell, final SimpleDBItem item, final String attributeName) {
super(parentShell);
this.item = item;
this.attributeName = attributeName;
this.values.addAll(this.item.attributes.get(this.attributeName));
}
}
| 8,000 |
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/DomainEditorInput.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.resource.ImageDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPersistableElement;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* Editor input for the custom query editor
*/
public class DomainEditorInput implements IEditorInput {
private final String domainName;
private final String accountId;
String getAccountId() {
return this.accountId;
}
String getDomainName() {
return this.domainName;
}
public DomainEditorInput(final String domainName, final String accountId) {
super();
this.domainName = domainName;
this.accountId = accountId;
}
@Override
@SuppressWarnings("rawtypes")
public Object getAdapter(final Class adapter) {
return null;
}
@Override
public boolean exists() {
return true;
}
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_TABLE);
}
@Override
public String getName() {
return this.domainName;
}
@Override
public IPersistableElement getPersistable() {
return null;
}
@Override
public String getToolTipText() {
return "Amazon SimpleDB Query Editor - " + this.domainName;
}
}
| 8,001 |
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/QueryEditor.java | package com.amazonaws.eclipse.datatools.enablement.simpledb.ui.editor;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.datatools.sqltools.sqlbuilder.views.source.SQLEditorDocumentProvider;
import org.eclipse.datatools.sqltools.sqlbuilder.views.source.SQLSourceEditingEnvironment;
import org.eclipse.datatools.sqltools.sqlbuilder.views.source.SQLSourceViewerConfiguration;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.source.AnnotationModel;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
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.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Sash;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.editors.text.EditorsPlugin;
import org.eclipse.ui.part.EditorPart;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.BrowserUtils;
import com.amazonaws.eclipse.core.ui.AbstractTableContentProvider;
import com.amazonaws.eclipse.core.ui.AbstractTableLabelProvider;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.SimpleDBItemName;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.model.BatchPutAttributesRequest;
import com.amazonaws.services.simpledb.model.Item;
import com.amazonaws.services.simpledb.model.ReplaceableAttribute;
import com.amazonaws.services.simpledb.model.ReplaceableItem;
import com.amazonaws.services.simpledb.model.SelectRequest;
import com.amazonaws.services.simpledb.model.SelectResult;
/**
* Editor to run queries and edit results
*/
public class QueryEditor extends EditorPart {
public static final String ID = "com.amazonaws.eclipse.datatools.enablement.simpledb.ui.editor.queryEditor";
private static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\s+"); //$NON-NLS-1$
private static final Pattern PATTERN_FROM_CLAUSE = Pattern.compile("from\\s+[\\S&&[^,]]+"); //$NON-NLS-1$
public static final char DELIMITED_IDENTIFIER_QUOTE = '`';
private DomainEditorInput domainEditorInput;
private TableViewer viewer;
boolean dirty;
private Map<String, Collection<EditedAttributeValue>> editedCells = new HashMap<>();
private String resultDomain;
private ToolBarManager toolBarManager;
private ToolBar toolBar;
private SourceViewer sqlSourceViewer;
private Composite sqlSourceViewerComposite;
private IDocument sqlSourceDocument;
private ExportAsCSVAction exportAsCSV;
private ContentProvider contentProvider;
@Override
public void doSave(final IProgressMonitor monitor) {
AmazonSimpleDB simpleDBClient = AwsToolkitCore.getClientFactory(this.domainEditorInput.getAccountId())
.getSimpleDBClient();
String domain = this.resultDomain;
ArrayList<ReplaceableItem> items = new ArrayList<>();
for ( String itemName : QueryEditor.this.editedCells.keySet() ) {
ReplaceableItem replaceableItem = new ReplaceableItem();
replaceableItem.setName(itemName);
Collection<ReplaceableAttribute> attributes = new LinkedList<>();
for ( EditedAttributeValue editedValue : QueryEditor.this.editedCells.get(itemName) ) {
if ( editedValue.newValue != null ) {
for ( String v : editedValue.newValue ) {
ReplaceableAttribute attr = new ReplaceableAttribute().withName(editedValue.name)
.withReplace(true).withValue(v);
attributes.add(attr);
}
}
}
if ( !attributes.isEmpty() ) {
items.add(replaceableItem);
replaceableItem.setAttributes(attributes);
}
}
if ( !items.isEmpty() ) {
simpleDBClient.batchPutAttributes(new BatchPutAttributesRequest(domain, items));
}
for ( String itemName : QueryEditor.this.editedCells.keySet() ) {
for ( EditedAttributeValue editedValue : QueryEditor.this.editedCells.get(itemName) ) {
QueryEditor.this.viewer.getTable().getItem(editedValue.row)
.setForeground(editedValue.col, Display.getDefault().getSystemColor(SWT.COLOR_BLACK));
}
}
QueryEditor.this.editedCells.clear();
this.dirty = false;
firePropertyChange(PROP_DIRTY);
}
@Override
public void doSaveAs() {
}
@Override
public void init(final IEditorSite site, final IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
this.domainEditorInput = (DomainEditorInput) input;
setPartName(input.getName());
}
@Override
public boolean isDirty() {
return this.dirty;
}
private void markDirty() {
this.dirty = true;
firePropertyChange(PROP_DIRTY);
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void createPartControl(final Composite composite) {
composite.setLayout(new FormLayout());
// Create the sash first, so the other controls
// can be attached to it.
final Sash sash = new Sash(composite, SWT.HORIZONTAL);
FormData data = new FormData();
// Initial position is a quarter of the way down the composite
data.top = new FormAttachment(25, 0);
// And filling 100% of horizontal space
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
sash.setLayoutData(data);
sash.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent event) {
// Move the sash to its new position and redraw it
((FormData) sash.getLayoutData()).top = new FormAttachment(0, event.y);
sash.getParent().layout();
}
});
this.toolBarManager = new ToolBarManager(SWT.LEFT);
this.toolBar = this.toolBarManager.createControl(composite);
configureSQLSourceViewer(composite);
data = new FormData();
data.top = new FormAttachment(0, 0);
data.bottom = new FormAttachment(this.sqlSourceViewerComposite, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
this.toolBar.setLayoutData(data);
data = new FormData();
data.top = new FormAttachment(this.toolBar, 0);
data.bottom = new FormAttachment(sash, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
this.sqlSourceViewerComposite.setLayoutData(data);
// Results table is attached to the top of the sash
Composite resultsComposite = new Composite(composite, SWT.BORDER);
data = new FormData();
data.top = new FormAttachment(sash, 0);
data.bottom = new FormAttachment(100, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
resultsComposite.setLayoutData(data);
createResultsTable(resultsComposite);
createActions();
}
private void configureSQLSourceViewer(final Composite composite) {
int VERTICAL_RULER_WIDTH = 12;
int styles = SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION;
ISharedTextColors sharedColors = EditorsPlugin.getDefault().getSharedTextColors();
CompositeRuler ruler = new CompositeRuler(VERTICAL_RULER_WIDTH);
try {
this.sqlSourceDocument = SQLEditorDocumentProvider.createDocument(getDefaultQuery());
} catch ( CoreException e ) {
e.printStackTrace();
}
AnnotationModel annotationModel = new AnnotationModel();
annotationModel.connect(this.sqlSourceDocument);
this.sqlSourceViewerComposite = new Composite(composite, SWT.BORDER);
this.sqlSourceViewerComposite.setLayout(new FillLayout());
this.sqlSourceViewer = new SourceViewer(this.sqlSourceViewerComposite, ruler, null, true, styles);
SQLSourceEditingEnvironment.connect();
SQLSourceViewerConfiguration configuration = new SQLSourceViewerConfiguration();
configuration.getCompletionProcessor().setCompletionProposalAutoActivationCharacters(new char[0]);
this.sqlSourceViewer.configure(configuration);
this.sqlSourceViewer.setDocument(this.sqlSourceDocument, annotationModel);
}
/**
* Creates actions for this editor
*/
private void createActions() {
this.toolBarManager.add(new OpenSelectSyntaxDocumentationAction());
this.toolBarManager.add(new Action() {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_START);
}
@Override
public String getText() {
return "Run query";
}
@Override
public String getToolTipText() {
return getText();
}
@Override
public void run() {
runQuery(QueryEditor.this.sqlSourceDocument.get());
}
@Override
public int getAccelerator() {
return SWT.CONTROL | SWT.ALT | 'x';
}
});
this.exportAsCSV = new ExportAsCSVAction();
this.exportAsCSV.setEnabled(false);
this.toolBarManager.add(this.exportAsCSV);
this.toolBarManager.update(true);
}
private static final String[] exportExtensions = new String[] { "*.csv" };
private class ExportAsCSVAction extends Action {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_EXPORT);
}
@Override
public String getText() {
return "Export as CSV";
}
@Override
public String getToolTipText() {
return "Export as comma-separated-value";
}
@Override
public void run() {
FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
dialog.setOverwrite(true);
dialog.setFilterExtensions(exportExtensions);
String csvFile = dialog.open();
if (csvFile != null) {
writeCsvFile(csvFile);
}
}
private void writeCsvFile(final String csvFile) {
try {
try (RandomAccessFile raf = new RandomAccessFile(new File(csvFile), "rw")) {
raf.setLength(0L);
}
List<SimpleDBItem> items = new LinkedList<>();
Set<String> columns = new LinkedHashSet<>();
for ( TableItem tableItem : QueryEditor.this.viewer.getTable().getItems() ) {
SimpleDBItem e = (SimpleDBItem) tableItem.getData();
columns.addAll(e.columns);
items.add(e);
}
try (BufferedWriter out = new BufferedWriter(new FileWriter(csvFile))) {
out.write(SimpleDBItemName.ITEM_HEADER);
for (String col : columns) {
out.write(",");
out.write(col);
}
out.write("\n");
for ( SimpleDBItem item : items ) {
out.write(item.itemName);
for (String col : columns) {
out.write(",");
Collection<String> values = item.attributes.get(col);
if (values != null) {
String value = join(values);
// For csv files, we need to quote all values and escape all quotes
value = value.replaceAll("\"", "\"\"");
value = "\"" + value + "\"";
out.write(value);
}
}
out.write("\n");
}
}
} catch (Exception e) {
AwsToolkitCore.getDefault().logError("Couldn't save CSV file", e);
}
}
}
private static class OpenSelectSyntaxDocumentationAction extends Action {
public static final String SIMPLEDB_SELECT_SYNTAX_DOCUMENTATION_URL =
"http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/index.html?UsingSelect.html";
public OpenSelectSyntaxDocumentationAction() {
this.setText("SimpleDB Select Syntax Documentation");
this.setToolTipText("View Amazon SimpleDB select query syntax documentation");
this.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_LCL_LINKTO_HELP));
}
@Override
public void run() {
BrowserUtils.openExternalBrowser(SIMPLEDB_SELECT_SYNTAX_DOCUMENTATION_URL);
}
}
private static String join(final Collection<String> values) {
return join(values, ",");
}
/**
* Joins a collection of attribute values, correctly handling single-value
* attributes and empty sets.
*/
private static String join(final Collection<String> values, final String separator) {
if ( values == null || values.isEmpty() ) {
return "";
}
if ( values.size() == 1 ) {
return values.iterator().next();
}
StringBuilder builder = new StringBuilder("[");
boolean seenOne = false;
for ( String s : values ) {
if ( seenOne ) {
builder.append(separator);
} else {
seenOne = true;
}
builder.append(s);
}
builder.append("]");
return builder.toString();
}
/**
* Updates the query results asynchronously. Must be called from the UI
* thread.
*/
private void runQuery(final String query) {
// Clear out the existing table
this.viewer.getTable().setEnabled(false);
this.exportAsCSV.setEnabled(false);
for ( TableColumn col : this.viewer.getTable().getColumns() ) {
col.dispose();
}
new Thread() {
@Override
public void run() {
SelectResult select = null;
try {
select = AwsToolkitCore.getClientFactory(QueryEditor.this.domainEditorInput.getAccountId()).getSimpleDBClient()
.select(new SelectRequest(query));
} catch ( Exception e ) {
AwsToolkitCore.getDefault().reportException(e.getMessage(), e);
return;
}
final SelectResult result = select;
QueryEditor.this.resultDomain = getDomainName(query);
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
QueryEditor.this.viewer.setInput(result);
QueryEditor.this.viewer.getTable().setEnabled(true);
QueryEditor.this.exportAsCSV.setEnabled(true);
QueryEditor.this.viewer.getTable().getParent().layout();
}
});
}
}.start();
}
private String convertSQLIdentifierToCatalogFormat(final String sqlIdentifier, final char idDelimiterQuote) {
String catalogIdentifier = sqlIdentifier;
if ( sqlIdentifier != null ) {
String delimiter = String.valueOf(idDelimiterQuote);
boolean isDelimited = sqlIdentifier.startsWith(delimiter) && sqlIdentifier.endsWith(delimiter);
boolean containsQuotedDelimiters = sqlIdentifier.indexOf(delimiter + delimiter) > -1;
if ( isDelimited ) {
catalogIdentifier = sqlIdentifier.substring(1, sqlIdentifier.length() - 1);
if ( containsQuotedDelimiters ) {
catalogIdentifier = catalogIdentifier.replaceAll(delimiter + delimiter, delimiter);
}
} else {
catalogIdentifier = sqlIdentifier;
}
}
return catalogIdentifier;
}
/**
* Returns the domain name from a select query.
*/
public String getDomainName(final String sql) {
Matcher m = PATTERN_FROM_CLAUSE.matcher(sql);
if ( m.find() ) {
String fromExpression = sql.substring(m.start(), m.end());
m = PATTERN_WHITESPACE.matcher(fromExpression);
if ( m.find() ) {
String domainName = convertSQLIdentifierToCatalogFormat(fromExpression.substring(m.end()),
DELIMITED_IDENTIFIER_QUOTE);
return domainName;
}
}
return null;
}
/**
* Creates the results table
*/
private void createResultsTable(final Composite resultsComposite) {
TableColumnLayout tableColumnLayout = new TableColumnLayout();
resultsComposite.setLayout(tableColumnLayout);
this.viewer = new TableViewer(resultsComposite);
this.viewer.getTable().setLinesVisible(true);
this.viewer.getTable().setHeaderVisible(true);
this.contentProvider = new ContentProvider();
this.viewer.setContentProvider(this.contentProvider);
this.viewer.setLabelProvider(new LabelProvider());
final Table table = this.viewer.getTable();
final TableEditor editor = new TableEditor(table);
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
TextCellEditorListener listener = new TextCellEditorListener(table, editor);
table.addListener(SWT.MouseUp, listener);
table.addListener(SWT.FocusOut, listener);
}
private String getDefaultQuery() {
return "select * from `" + this.domainEditorInput.getDomainName() + "`";
}
@Override
public void setFocus() {
}
/**
* Listener to respond to clicks in a cell, invoking a cell editor
*/
private final class TextCellEditorListener implements Listener {
private final Table table;
private final TableEditor editor;
private Composite editorComposite;
private Text editorText;
private Button button;
private TextCellEditorListener(final Table table, final TableEditor editor) {
this.table = table;
this.editor = editor;
}
@Override
public void handleEvent(final Event event) {
if ( event.type == SWT.FocusOut && this.editorComposite != null && !this.editorComposite.isDisposed() ) {
Control focus = Display.getCurrent().getFocusControl();
if ( focus != this.editorComposite && focus != this.editorText && focus != this.table ) {
this.editorComposite.dispose();
}
}
Rectangle clientArea = this.table.getClientArea();
Point pt = new Point(event.x, event.y);
int row = this.table.getTopIndex();
while ( row < this.table.getItemCount() ) {
boolean visible = false;
final TableItem item = this.table.getItem(row);
// We don't care about clicks in the first column since they
// are read-only
for ( int col = 1; col < this.table.getColumnCount(); col++ ) {
Rectangle rect = item.getBounds(col);
if ( rect.contains(pt) ) {
if ( this.editorComposite != null && !this.editorComposite.isDisposed() ) {
this.editorComposite.dispose();
}
// If this is a multi-value item, don't allow textual
// editing
SimpleDBItem simpleDBItem = (SimpleDBItem) item.getData();
final String attributeName = item.getParent().getColumn(col).getText();
if ( simpleDBItem.attributes.containsKey(attributeName)
&& simpleDBItem.attributes.get(attributeName).size() > 1 ) {
invokeMultiValueDialog(item, attributeName, col, row);
return;
}
createEditor();
final int column = col;
final int rowNum = row;
this.editor.setEditor(this.editorComposite, item, col);
this.editorText.setText(item.getText(col));
this.editorText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(final ModifyEvent e) {
markModified(item, column, rowNum, TextCellEditorListener.this.editorText);
}
});
this.editorText.addTraverseListener(new TraverseListener() {
@Override
public void keyTraversed(final TraverseEvent e) {
TextCellEditorListener.this.editorComposite.dispose();
}
});
this.button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
invokeMultiValueDialog(item, attributeName, column, rowNum);
TextCellEditorListener.this.editorComposite.dispose();
}
});
this.editorText.selectAll();
this.editorText.setFocus();
return;
}
if ( !visible && rect.intersects(clientArea) ) {
visible = true;
}
}
if ( !visible ) {
return;
}
row++;
}
}
private void createEditor() {
this.editorComposite = new Composite(this.table, SWT.None);
this.editorComposite.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE));
GridLayout layout = new GridLayout(2, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
layout.horizontalSpacing = 0;
this.editorComposite.setLayout(layout);
this.editorText = new Text(this.editorComposite, SWT.None);
GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.TOP).grab(true, true).indent(2, 2)
.applyTo(this.editorText);
this.button = new Button(this.editorComposite, SWT.None);
this.button.setText("...");
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.TOP).grab(false, true).applyTo(this.button);
this.button.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE));
}
private void invokeMultiValueDialog(final TableItem item,
final String attributeName,
final int column,
final int row) {
SimpleDBItem simpleDBItem = (SimpleDBItem) item.getData();
MultiValueAttributeEditorDialog multiValueEditorDialog = new MultiValueAttributeEditorDialog(Display.getDefault()
.getActiveShell(), simpleDBItem, attributeName);
int returnValue = multiValueEditorDialog.open();
if ( returnValue == 0 ) {
markModified(item, column, row, multiValueEditorDialog.getValues());
}
}
}
private class LabelProvider extends AbstractTableLabelProvider {
@Override
public String getColumnText(final Object element, final int columnIndex) {
SimpleDBItem item = (SimpleDBItem) element;
if ( columnIndex == 0 ) {
return item.itemName;
}
// Column index is offset by one to make room for item name
String column = QueryEditor.this.contentProvider.getColumns()[columnIndex - 1];
Collection<String> values = item.attributes.get(column);
return join(values);
}
}
private class ContentProvider extends AbstractTableContentProvider {
private SelectResult input;
private Object[] elements;
private String[] columns;
@Override
public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) {
this.input = (SelectResult) newInput;
this.elements = null;
initializeElements();
if ( this.input != null ) {
Table table = (Table) viewer.getControl();
TableColumnLayout layout = (TableColumnLayout) table.getParent().getLayout();
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(SimpleDBItemName.ITEM_HEADER);
layout.setColumnData(column, new ColumnWeightData(10));
for ( String col : this.columns ) {
column = new TableColumn(table, SWT.NONE);
column.setText(col);
layout.setColumnData(column, new ColumnWeightData(10));
}
}
}
@Override
public Object[] getElements(final Object inputElement) {
initializeElements();
return this.elements;
}
private synchronized void initializeElements() {
if ( this.elements == null && this.input != null ) {
List<SimpleDBItem> items = new LinkedList<>();
Set<String> columns = new LinkedHashSet<>();
for ( Item item : this.input.getItems() ) {
SimpleDBItem e = new SimpleDBItem(item);
columns.addAll(e.columns);
items.add(e);
}
this.elements = items.toArray();
this.columns = columns.toArray(new String[columns.size()]);
}
}
private synchronized String[] getColumns() {
return this.columns;
}
}
/**
* Container for edited attributes
*/
private class EditedAttributeValue {
private String name;
private Collection<String> newValue;
int row;
int col;
@Override
public String toString() {
return "name: " + this.name + "; new: " + this.newValue;
}
}
/**
* Marks the given tree item and column modified.
*/
protected void markModified(final TableItem item, final int column, final int row, final Text text) {
List<String> values = new LinkedList<>();
values.add(text.getText());
markModified(item, column, row, values);
}
/**
* Marks the given tree item and column modified.
*/
protected void markModified(final TableItem item, final int column, final int row, final Collection<String> newValue) {
item.setText(column, join(newValue));
SimpleDBItem simpleDBItem = (SimpleDBItem) item.getData();
String itemName = simpleDBItem.itemName;
String attributeName = item.getParent().getColumn(column).getText();
// Update the data model with this new value
simpleDBItem.attributes.put(attributeName, newValue);
// Bootstrap new items
if ( !this.editedCells.containsKey(itemName) ) {
this.editedCells.put(itemName, new LinkedList<EditedAttributeValue>());
}
// Find this value in the list and update it
EditedAttributeValue value = null;
for ( EditedAttributeValue v : this.editedCells.get(itemName) ) {
if ( v.name.equals(attributeName) ) {
value = v;
break;
}
}
// Create the edited value if this is the first time we've edited it
if ( value == null ) {
value = new EditedAttributeValue();
value.name = attributeName;
value.col = column;
value.row = row;
this.editedCells.get(itemName).add(value);
}
value.newValue = newValue;
// Finally update the table UI to reflect the edit
item.setForeground(column, Display.getDefault().getSystemColor(SWT.COLOR_RED));
markDirty();
}
}
| 8,002 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/connection/SimpleDBConnectionUtils.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.connection;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
/**
* Utility functions for SimpleDB connections, such as listing the available
* SimpleDB service endpoints, the default endpoint, and for filling in missing
* required properties in connection profile properties.
*
* @author Jason Fulghum <fulghum@amazon.com>
*/
public class SimpleDBConnectionUtils {
/** Properties file key for the list of available SimpleDB endpoints */
private static final String ENDPOINTS_PROPERTY = "endpoints"; //$NON-NLS-1$
/** Properties file key for the default SimpleDB endpoint */
private static final String DEFAULT_ENDPOINT_PROPERTY = "defaultEndpoint"; //$NON-NLS-1$
/**
* The backup SimpleDB endpoint to use if we run into any problems loading
* the data from the connection properties file.
*/
private static final String SIMPLEDB_BACKUP_ENDPOINT = "sdb.amazonaws.com"; //$NON-NLS-1$
/**
* Returns the default endpoint to use for SimpleDB connections.
*
* @return The default endpoint to use for SimpleDB connections.
*/
public String getDefaultEndpoint() {
String endpoint = lookupConnectionProperty(DEFAULT_ENDPOINT_PROPERTY);
if (endpoint != null) {
return endpoint;
}
return SIMPLEDB_BACKUP_ENDPOINT;
}
/**
* Returns a map of available SimpleDB service endpoints, keyed by the
* associated region name.
*
* @return A map of available SimpleDB service endpoints, keyed by the
* associated region name.
*/
public Map<String, String> getAvailableEndpoints() {
String endpointsPropertyValue = lookupConnectionProperty(ENDPOINTS_PROPERTY);
if (endpointsPropertyValue != null) {
Map<String, String> availableEndpointsByRegionName = new LinkedHashMap<>();
for (String endpointRecord : endpointsPropertyValue.split(",")) {
endpointRecord = endpointRecord.trim();
// Find the last space in the endpoint record so that we can pull
// out everything after that as the endpoint, and everything before
// that as the region label.
int recordSeparatorIndex = endpointRecord.lastIndexOf(" ");
String regionName = endpointRecord.substring(0, recordSeparatorIndex);
String endpoint = endpointRecord.substring(recordSeparatorIndex + 1);
availableEndpointsByRegionName.put(regionName, endpoint);
}
return availableEndpointsByRegionName;
}
Map<String, String> defaultEndpoint = new HashMap<>();
defaultEndpoint.put("US-East", SIMPLEDB_BACKUP_ENDPOINT);
return defaultEndpoint;
}
/**
* Initializes any required SimpleDB connection profile properties to safe
* defaults if they are missing.
*
* <p>
* For example, if the user has a connection profile, created with an older
* version of the tools, that is missing a new required parameter, this
* method will handle assigning it a reasonable default value.
*/
public void initializeMissingProperties(final Properties properties) {
/*
* The first version of the toolkit didn't allow users to use multiple
* service endpoints, so if we detect that we don't have an endpoint
* set, we know to default to the original endpoint, sdb.amazonaws.com.
*/
String endpoint = properties.getProperty(ISimpleDBConnectionProfileConstants.ENDPOINT);
if (endpoint == null) {
endpoint = getDefaultEndpoint();
properties.setProperty(ISimpleDBConnectionProfileConstants.ENDPOINT, endpoint);
}
String accountId = properties.getProperty(ISimpleDBConnectionProfileConstants.ACCOUNT_ID);
if (accountId == null) {
accountId = AwsToolkitCore.getDefault().getCurrentAccountId();
properties.setProperty(ISimpleDBConnectionProfileConstants.ACCOUNT_ID, accountId);
}
}
/*
* Private Interface
*/
/**
* Looks up the specified property in the connection properties file and
* returns the (trimmed) value. If there is no value specified, or the value
* specified is a blank string, or if the connection properties file can't
* be read, then null is returned.
*
* @param propertyName
* The name of the property to look up.
*
* @return The value of the specified property, otherwise null if the
* property wasn't found, the properties file couldn't be read, or
* the property was an empty string.
*/
private String lookupConnectionProperty(final String propertyName) {
URL resource = Activator.getDefault().getBundle().getResource("properties/connection.properties");
try {
Properties properties = new Properties();
properties.load(resource.openStream());
String propertyValue = properties.getProperty(propertyName);
// Bail out and return null if we didn't find a property by that name
if (propertyValue == null) {
return null;
}
// Otherwise trim it and return it if it has real content
propertyValue = propertyValue.trim();
if (propertyValue.length() > 0) {
return propertyValue;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| 8,003 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/connection/ISimpleDBConnectionProfileConstants.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.connection;
/**
* Common property names for the core and UI plugins.
*/
public interface ISimpleDBConnectionProfileConstants {
public static final String SIMPLEDB_PROFILE_PROVIDER_ID = "com.amazonaws.eclipse.datatools.enablement.simpledb.connectionProfile"; //$NON-NLS-1$
public static final String SIMPLEDB_DRIVER_ID = "DriverDefn.com.amazonaws.eclipse.datatools.enablement.simpledb.driverTemplate.Amazon SimpleDB Driver Default"; //$NON-NLS-1$
public static final String SIMPLEDB_CATEGORY_ID = "com.amazonaws.eclipse.datatools.enablement.simpledb.driverCategory"; //$NON-NLS-1$
public static final String ENDPOINT = "com.amazonaws.eclipse.datatools.enablement.simpledb.endpoint"; //$NON-NLS-1$
public static final String ACCOUNT_ID = "com.amazonaws.eclipse.datatools.enablement.simpledb.accountId"; //$NON-NLS-1$
}
| 8,004 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/driver/SimpleDBItemName.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.driver;
/**
* Wrapper around the item name to distinguish between usual and itemName strings in the UI and to forbid editing the
* itemName once it was persisted to the SDB.
*/
public class SimpleDBItemName {
private String itemName;
private boolean persisted;
/** This name is used in select queries and in the UI to represent the itemName value */
public static final String ITEM_HEADER = "itemName()"; //$NON-NLS-1$
/**
* @param itemName
*/
public SimpleDBItemName(final String itemName) {
this.itemName = itemName;
}
/**
* @param itemName
* @param persisted
*/
public SimpleDBItemName(final String itemName, final boolean persisted) {
this.itemName = itemName;
this.persisted = persisted;
}
/**
* @param itemName
*/
public void setItemName(final String itemName) {
this.itemName = itemName;
}
/**
* @return
*/
public String getItemName() {
return this.itemName;
}
/**
* @param persisted
* <code>true</code> if itemName is saved to SDB or came from SDB
*/
public void setPersisted(final boolean persisted) {
this.persisted = persisted;
}
/**
* @return <code>true</code> if itemName is saved to SDB or came from SDB
*/
public boolean isPersisted() {
return this.persisted;
}
@Override
public String toString() {
return this.itemName;
}
}
| 8,005 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/driver/JdbcConnection.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.driver;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import com.amazonaws.eclipse.datatools.enablement.simpledb.internal.driver.JdbcDatabaseMetaData;
import com.amazonaws.eclipse.datatools.enablement.simpledb.internal.driver.JdbcPreparedStatement;
import com.amazonaws.eclipse.datatools.enablement.simpledb.internal.driver.JdbcStatement;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
/**
* JDBC Connection wrapper around AmazonSimpleDB driver.
*/
public class JdbcConnection implements Connection {
private JdbcDriver driver;
private String accessKey;
private String secretKey;
private boolean readOnly = false;
private boolean autoCommit = true;
private JdbcDatabaseMetaData metaData;
/** Map of domain_name to list of attribute_name, where attributes are temporary ones not yet existing in the SDB. */
private Map<String, List<String>> pendingColumns = new HashMap<>();
/** The SimpleDB service endpoint this JDBC driver will talk to */
private final String endpoint;
/**
* Creates a new JDBC connection to Amazon SimpleDB, using the specified
* driver to connect to the specified endpoint, and the access key and
* secret key to authenticate.
*
* @param driver
* The SimpleDB JDBC Driver object to use to communicate to
* SimpleDB.
* @param accessKey
* The AWS access key for the desired account.
* @param secretKey
* The AWS secret access key for the desired account.
* @param endpoint
* The Amazon SimpleDB endpoint to communicate with.
*/
public JdbcConnection(final JdbcDriver driver, final String accessKey, final String secretKey, final String endpoint) {
this.driver = driver;
this.accessKey = accessKey;
this.secretKey = secretKey;
this.endpoint = endpoint;
}
/**
* @return an instance of the AmazonSDB driver
*/
public AmazonSimpleDB getClient() {
try {
return this.driver.getClient(this.accessKey, this.secretKey, this.endpoint);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public void close() throws SQLException {
this.driver = null;
this.accessKey = null;
this.secretKey = null;
}
@Override
public void commit() throws SQLException {
assertOpen();
// close();
}
@Override
public void rollback() throws SQLException {
assertOpen();
// close();
}
private void assertCursorOptions(final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) throws SQLException {
if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) {
throw new SQLException("Only TYPE_FORWARD_ONLY cursor is supported"); //$NON-NLS-1$
}
if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) {
throw new SQLException("Only CONCUR_READ_ONLY cursor is supported"); //$NON-NLS-1$
}
if (resultSetHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) {
throw new SQLException("Only CLOSE_CURSORS_AT_COMMIT is supported"); //$NON-NLS-1$
}
}
private void assertOpen() throws SQLException {
if (this.driver == null) {
throw new SQLException("database connection closed"); //$NON-NLS-1$
}
}
@Override
public Statement createStatement() throws SQLException {
return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public Statement createStatement(final int resultSetType, final int resultSetConcurrency) throws SQLException {
return createStatement(resultSetType, resultSetConcurrency, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public Statement createStatement(final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) throws SQLException {
assertCursorOptions(resultSetType, resultSetConcurrency, resultSetHoldability);
return new JdbcStatement(this);
}
@Override
public boolean getAutoCommit() throws SQLException {
return this.autoCommit;
}
@Override
public String getCatalog() throws SQLException {
assertOpen();
return null;
}
@Override
public void setCatalog(final String catalog) throws SQLException {
assertOpen();
}
@Override
public int getHoldability() throws SQLException {
assertOpen();
return ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
@Override
public void setHoldability(final int holdability) throws SQLException {
assertOpen();
if (holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT) {
throw new SQLException("Only CLOSE_CURSORS_AT_COMMIT cursor is supported"); //$NON-NLS-1$
}
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
if (this.metaData == null) {
this.metaData = new JdbcDatabaseMetaData(this);
}
return this.metaData;
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public boolean isClosed() throws SQLException {
return this.driver == null;
}
@Override
public boolean isReadOnly() throws SQLException {
return this.readOnly;
}
@Override
public String nativeSQL(final String sql) throws SQLException {
return sql;
}
@Override
public CallableStatement prepareCall(final String sql) throws SQLException {
return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency)
throws SQLException {
return prepareCall(sql, resultSetType, resultSetConcurrency, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) throws SQLException {
throw new SQLException("SimpleDB does not support Stored Procedures"); //$NON-NLS-1$
}
@Override
public PreparedStatement prepareStatement(final String sql) throws SQLException {
return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) throws SQLException {
// NB! ignores autoGeneratedKeys
return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public PreparedStatement prepareStatement(final String sql, final int[] columnIndexes) throws SQLException {
// NB! ignores columnIndexes
return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public PreparedStatement prepareStatement(final String sql, final String[] columnNames) throws SQLException {
// NB! ignores columnNames
return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency)
throws SQLException {
return prepareStatement(sql, resultSetType, resultSetConcurrency, ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
@Override
public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) throws SQLException {
assertCursorOptions(resultSetType, resultSetConcurrency, resultSetHoldability);
return new JdbcPreparedStatement(this, sql);
}
@Override
public void setAutoCommit(final boolean autoCommit) throws SQLException {
this.autoCommit = autoCommit;
}
@Override
public void setReadOnly(final boolean readOnly) throws SQLException {
this.readOnly = readOnly;
}
@Override
public int getTransactionIsolation() {
return TRANSACTION_SERIALIZABLE;
}
@Override
public void setTransactionIsolation(final int level) throws SQLException {
if (level != TRANSACTION_SERIALIZABLE) {
throw new SQLException("SDB supports only TRANSACTION_SERIALIZABLE"); //$NON-NLS-1$
}
}
// NOT SUPPORTED ////////////////////////////////////////////////////////////
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
}
@Override
public void setTypeMap(final Map<String, Class<?>> map) throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
}
@Override
public Savepoint setSavepoint() throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
}
@Override
public Savepoint setSavepoint(final String name) throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
}
@Override
public void releaseSavepoint(final Savepoint savepoint) throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
}
@Override
public void rollback(final Savepoint savepoint) throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
}
//////////////////////////////////////////////////////////////////////////////
/**
* Temporarily holds an attribute which can't be added directly to SDB without a value.
*
* @param table
* domain name
* @param column
* attribute name
*/
public void addPendingColumn(final String table, final String column) {
List<String> columns = this.pendingColumns.get(table);
if (columns == null) {
columns = new ArrayList<>();
this.pendingColumns.put(table, columns);
}
if (!columns.contains(column)) {
columns.add(column);
}
}
/**
* Removes temporary attribute when it's no longer needed.
*
* @param table
* @param column
* @return <code>true</code> if pending columns list contained the specified column
*/
public boolean removePendingColumn(final String table, final String column) {
List<String> columns = this.pendingColumns.get(table);
if (columns != null) {
boolean result = columns.remove(column);
if (columns.isEmpty()) {
this.pendingColumns.remove(table);
}
return result;
}
return false;
}
/**
* A list of temporary attributes to be returned by JDBC driver, but not existing in SDB yet since there is no values.
*
* @param table
* domain name
* @return list of attribute names
*/
public List<String> getPendingColumns(final String table) {
return this.pendingColumns.get(table);
}
@Override
public Array createArrayOf(final String typeName, final Object[] elements)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Struct createStruct(final String typeName, final Object[] attributes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getClientInfo(final String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isValid(final int timeout) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void setClientInfo(final Properties properties)
throws SQLClientInfoException {
// TODO Auto-generated method stub
}
@Override
public void setClientInfo(final String name, final String value)
throws SQLClientInfoException {
// TODO Auto-generated method stub
}
@Override
public boolean isWrapperFor(final Class<?> arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(final Class<T> arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setSchema(String schema) throws SQLException {
}
@Override
public String getSchema() throws SQLException {
return null;
}
@Override
public void abort(Executor executor) throws SQLException {
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds)
throws SQLException {
}
@Override
public int getNetworkTimeout() throws SQLException {
return 0;
}
}
| 8,006 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/driver/JdbcDriver.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.driver;
import java.lang.reflect.Constructor;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;
import org.eclipse.core.net.proxy.IProxyData;
import org.eclipse.core.net.proxy.IProxyService;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.eclipse.core.AwsClientUtils;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.model.ListDomainsRequest;
/**
* Creates a JDBC wrapper infrastructure around AmazonSDB client library.
*/
public class JdbcDriver implements Driver {
private final Class<?> driverClass;
/**
* Creates a JDBC wrapper infrastructure around AmazonSDB client library.
*
* @param driverClass
* AmazonSDB client class
*/
public JdbcDriver(final Class<?> driverClass) {
this.driverClass = driverClass;
}
/* (non-Javadoc)
* @see java.sql.Driver#acceptsURL(java.lang.String)
*/
@Override
public boolean acceptsURL(final String url) throws SQLException {
return false;
}
/**
* @param url
* is not used
* @param info
* properties contain users access and secret keys as 'user' and 'password'
* @return {@link JdbcConnection}
* @throws SQLException
*/
@Override
public Connection connect(final String url, final Properties info) throws SQLException {
String access = info.getProperty("user"); //$NON-NLS-1$
String secret = info.getProperty("password"); //$NON-NLS-1$
String endpoint = info.getProperty("endpoint"); //$NON-NLS-1$
if (access == null || access.trim().length() == 0 || secret == null || secret.trim().length() == 0) {
throw new SQLException("AWS access credentials are missing", "08001", 8001); //$NON-NLS-1$ //$NON-NLS-2$
}
if (endpoint == null || endpoint.trim().length() == 0) {
throw new SQLException("Endpoint is missing", "08001", 8001); //$NON-NLS-1$ //$NON-NLS-2$
}
try {
// testing to fail early
AmazonSimpleDB service = getClient(access, secret, endpoint);
ListDomainsRequest req = new ListDomainsRequest();
req.setMaxNumberOfDomains(10);
service.listDomains(req);
JdbcConnection conn = new JdbcConnection(this, access, secret, endpoint);
return conn;
} catch (AmazonServiceException e) {
SQLException se = new SQLException(e.getLocalizedMessage(), "08001", e.getStatusCode()); //$NON-NLS-1$
se.initCause(e);
throw se;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
SQLException se = new SQLException(e.getLocalizedMessage(), "08001", 8001); //$NON-NLS-1$
se.initCause(e);
throw se;
}
}
/**
* Returns an Amazon SimpleDB client, configured with the specified access
* key, secret key, and endpoint.
*
* @param access
* The AWS access key to use for authentication in the returned
* client.
* @param secret
* The AWS secret access key to use for authentication in the
* returned client.
* @param endpoint
* The SimpleDB service endpoint that the returned client should
* communicate with.
*
* @return An Amazon SimpleDB client, configured with the specified access
* key, secret key, and endpoint.
*
* @throws SQLException
* If any problems are encountered creating the client to
* return.
*/
public AmazonSimpleDB getClient(final String access, final String secret, final String endpoint) throws SQLException {
try {
AWSCredentials credentials = new BasicAWSCredentials(access, secret);
String userAgent = AwsClientUtils.formatUserAgentString("SimpleDBEclipsePlugin", Activator.getDefault()); //$NON-NLS-1$
ClientConfiguration config = new ClientConfiguration();
config.setUserAgent(userAgent);
Activator plugin = Activator.getDefault();
if (plugin != null) {
IProxyService proxyService = AwsToolkitCore.getDefault().getProxyService();
if (proxyService.isProxiesEnabled()) {
IProxyData proxyData = proxyService.getProxyDataForHost(endpoint, IProxyData.HTTPS_PROXY_TYPE);
if (proxyData != null) {
config.setProxyHost(proxyData.getHost());
config.setProxyPort(proxyData.getPort());
if (proxyData.isRequiresAuthentication()) {
config.setProxyUsername(proxyData.getUserId());
config.setProxyPassword(proxyData.getPassword());
}
}
}
}
Constructor<?> cstr = this.driverClass.getConstructor(new Class[] { AWSCredentials.class, ClientConfiguration.class });
AmazonSimpleDB service = (AmazonSimpleDB) cstr.newInstance(new Object[] { credentials, config });
service.setEndpoint("https://" + endpoint.trim());
return service;
} catch (Exception e) {
SQLException se = new SQLException(e.getLocalizedMessage(), "08001", 8001); //$NON-NLS-1$
se.initCause(e);
throw se;
}
}
@Override
public int getMajorVersion() {
return 1;
}
@Override
public int getMinorVersion() {
return 0;
}
@Override
public DriverPropertyInfo[] getPropertyInfo(final String url, final Properties info) throws SQLException {
return new DriverPropertyInfo[0];
}
@Override
public boolean jdbcCompliant() {
return false;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
}
| 8,007 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/SimpleDBOverviewSection.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.enablement.simpledb.internal.ui;
import org.eclipse.datatools.connectivity.ui.actions.AddProfileViewAction;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.WorkbenchException;
import com.amazonaws.eclipse.core.AwsUrls;
import com.amazonaws.eclipse.core.ui.overview.OverviewSection;
/**
* Amazon SimpleDB OverviewSection implementation that provides overview content
* for the SimpleDB Management functionality in the AWS Toolkit for Eclipse
* (links to docs, shortcuts for creating new connections to SimpleDB, etc.)
*/
public class SimpleDBOverviewSection extends OverviewSection implements OverviewSection.V2 {
private static final String SIMPLEDB_ECLIPSE_GETTING_STARTED_GUIDE_URL =
"http://aws.amazon.com/eclipse/simpledb/gsg" + "?" + AwsUrls.TRACKING_PARAMS;
private static final String SIMPLEDB_ECLIPSE_SCREENCAST_URL =
"http://media.amazonwebservices.com/videos/eclipse-sdb-management-video.html" + "?" + AwsUrls.TRACKING_PARAMS;
/* (non-Javadoc)
* @see com.amazonaws.eclipse.core.ui.overview.OverviewSection#createControls(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createControls(final Composite parent) {
Composite tasksSection = this.toolkit.newSubSection(parent, "Tasks");
this.toolkit.newListItem(tasksSection,
"Connect to Amazon SimpleDB", null, new CreateNewSimpleDBConnectionAction());
Composite resourcesSection = this.toolkit.newSubSection(parent, "Additional Resources");
this.toolkit.newListItem(resourcesSection,
"Video: Overview of Amazon SimpleDB Management in Eclipse",
SIMPLEDB_ECLIPSE_SCREENCAST_URL, null);
this.toolkit.newListItem(resourcesSection,
"Getting Started with Amazon SimpleDB Management in Eclipse",
SIMPLEDB_ECLIPSE_GETTING_STARTED_GUIDE_URL, null);
}
/**
* Action class that opens the DTP Database Development perspective, and
* brings up the new connection profile wizard.
*/
private static class CreateNewSimpleDBConnectionAction extends Action {
/** The ID of the Database Development perspective provided by DTP */
private static final String DATABASE_DEVELOPMENT_PERSPECTIVE_ID =
"org.eclipse.datatools.sqltools.sqleditor.perspectives.EditorPerspective";
@Override
public void run() {
try {
PlatformUI.getWorkbench().showPerspective(DATABASE_DEVELOPMENT_PERSPECTIVE_ID,
PlatformUI.getWorkbench().getActiveWorkbenchWindow());
} catch (WorkbenchException e) {
e.printStackTrace();
}
new AddProfileViewAction().run();
}
}
}
| 8,008 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/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.enablement.simpledb.internal.ui;
import org.eclipse.osgi.util.NLS;
public class Messages {
private static final String BUNDLE_NAME = "com.amazonaws.eclipse.datatools.enablement.simpledb.internal.ui.messages"; //$NON-NLS-1$
public static String CUI_NEWCW_ENDPOINT_LBL_UI_;
public static String CUI_NEWCW_VALIDATE_IDENTITY_REQ_UI_;
public static String CUI_NEWCW_VALIDATE_SECRET_REQ_UI_;
public static String database;
public static String itemName_and_attributes;
private Messages() {
}
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
}
| 8,009 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/connection/NewSimpleDBConnectionProfileWizard.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.internal.ui.connection;
import org.eclipse.datatools.connectivity.ui.wizards.ExtensibleNewConnectionProfileWizard;
public class NewSimpleDBConnectionProfileWizard extends ExtensibleNewConnectionProfileWizard {
public NewSimpleDBConnectionProfileWizard() {
super(new SimpleDBProfileDetailsWizardPage(
"com.amazonaws.eclipse.datatools.enablement.simpledb.internal.ui.connection.SimpleDBProfileDetailsWizardPage")); //$NON-NLS-1$
}
}
| 8,010 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/connection/SimpleDBProfileDetailsWizardPage.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.internal.ui.connection;
import org.eclipse.datatools.connectivity.ui.wizards.ExtensibleProfileDetailsWizardPage;
import com.amazonaws.eclipse.datatools.enablement.simpledb.connection.ISimpleDBConnectionProfileConstants;
public class SimpleDBProfileDetailsWizardPage extends ExtensibleProfileDetailsWizardPage {
public SimpleDBProfileDetailsWizardPage(final String pageName) {
super(pageName, ISimpleDBConnectionProfileConstants.SIMPLEDB_CATEGORY_ID);
}
}
| 8,011 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/connection/SimpleDBProfilePropertyPage.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.internal.ui.connection;
import org.eclipse.datatools.connectivity.ui.wizards.ExtensibleProfileDetailsPropertyPage;
import com.amazonaws.eclipse.datatools.enablement.simpledb.connection.ISimpleDBConnectionProfileConstants;
public class SimpleDBProfilePropertyPage extends ExtensibleProfileDetailsPropertyPage {
public SimpleDBProfilePropertyPage() {
super(ISimpleDBConnectionProfileConstants.SIMPLEDB_CATEGORY_ID);
}
}
| 8,012 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/connection | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/connection/drivers/SimpleDBOtherDriverUIContributor.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.internal.ui.connection.drivers;
import org.eclipse.datatools.connectivity.ui.wizards.OtherDriverUIContributor;
public class SimpleDBOtherDriverUIContributor extends OtherDriverUIContributor {
}
| 8,013 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/connection | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/connection/drivers/SimpleDBDriverUIContributor.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.internal.ui.connection.drivers;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.eclipse.datatools.connectivity.drivers.jdbc.IJDBCDriverDefinitionConstants;
import org.eclipse.datatools.connectivity.ui.wizards.IDriverUIContributor;
import org.eclipse.datatools.connectivity.ui.wizards.IDriverUIContributorInformation;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.AccountSelectionComposite;
import com.amazonaws.eclipse.datatools.enablement.simpledb.connection.ISimpleDBConnectionProfileConstants;
import com.amazonaws.eclipse.datatools.enablement.simpledb.connection.SimpleDBConnectionUtils;
import com.amazonaws.eclipse.datatools.enablement.simpledb.internal.ui.Messages;
public class SimpleDBDriverUIContributor implements IDriverUIContributor, Listener {
private static final String DATABASE_LABEL = Messages.database;
/**
* * Name of resource property for the selection of workbench or project settings **
*/
public static final String USE_PROJECT_SETTINGS = "useProjectSettings"; //$NON-NLS-1$
protected IDriverUIContributorInformation contributorInformation;
private ScrolledComposite parentComposite;
private Properties properties;
private boolean isReadOnly = false;
/** Combo control for users to select the SimpleDB endpoint */
private Combo endpointCombo;
private AccountSelectionComposite accountSelection;
/**
* SimpleDB connection utils, listing endpoints, filling in missing required
* properties, etc.
*/
private SimpleDBConnectionUtils simpleDBConnectionUtils = new SimpleDBConnectionUtils();
private DialogPage parentPage;
/**
* @see org.eclipse.datatools.connectivity.ui.wizards.IDriverUIContributor#determineContributorCompletion()
*/
@Override
public boolean determineContributorCompletion() {
return accountValid();
}
protected boolean accountValid() {
String accountId = this.accountSelection.getSelectedAccountId();
return AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(accountId).isValid();
}
/**
* @see org.eclipse.datatools.connectivity.ui.wizards.IDriverUIContributor#getContributedDriverUI(org.eclipse.swt.widgets.Composite, boolean)
*/
@Override
public Composite getContributedDriverUI(final Composite parent, final boolean isReadOnly) {
if ((this.parentComposite == null) || this.parentComposite.isDisposed() || (this.isReadOnly != isReadOnly)) {
GridData gd;
this.isReadOnly = isReadOnly;
this.parentComposite = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
this.parentComposite.setExpandHorizontal(true);
this.parentComposite.setExpandVertical(true);
this.parentComposite.setLayout(new GridLayout());
Composite baseComposite = new Composite(this.parentComposite, SWT.NULL);
GridLayout layout = new GridLayout();
layout.numColumns = 3;
baseComposite.setLayout(layout);
Label endpointLabel = new Label(baseComposite, SWT.NONE);
endpointLabel.setText(Messages.CUI_NEWCW_ENDPOINT_LBL_UI_);
gd = new GridData();
gd.verticalAlignment = GridData.CENTER;
gd.horizontalSpan = 1;
endpointLabel.setLayoutData(gd);
this.endpointCombo = new Combo(baseComposite, SWT.READ_ONLY);
gd = new GridData();
gd.horizontalAlignment = GridData.FILL;
gd.verticalAlignment = GridData.BEGINNING;
gd.grabExcessHorizontalSpace = true;
gd.horizontalSpan = 2;
this.endpointCombo.setLayoutData(gd);
Map<String, String> availableEndpointsByRegionName = this.simpleDBConnectionUtils.getAvailableEndpoints();
for (String regionName : availableEndpointsByRegionName.keySet()) {
String endpoint = availableEndpointsByRegionName.get(regionName);
String text = regionName;
this.endpointCombo.add(text);
this.endpointCombo.setData(text, endpoint);
}
Composite header = createHeader(baseComposite);
gd = new GridData();
gd.horizontalAlignment = GridData.FILL;
gd.verticalAlignment = GridData.BEGINNING;
gd.verticalIndent = 10;
gd.grabExcessHorizontalSpace = true;
gd.horizontalSpan = 3;
header.setLayoutData(gd);
this.parentComposite.setContent(baseComposite);
this.parentComposite.setMinSize(baseComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
initialize();
}
return this.parentComposite;
}
private Composite createHeader(final Composite parent) {
this.accountSelection = new AccountSelectionComposite(parent, SWT.NONE);
this.accountSelection.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
return this.accountSelection;
}
/**
* @see org.eclipse.datatools.connectivity.ui.wizards.IDriverUIContributor#getSummaryData()
*/
@Override
public List<String[]> getSummaryData() {
return Collections.emptyList();
}
/**
* @see org.eclipse.datatools.connectivity.ui.wizards.IDriverUIContributor#loadProperties()
*/
@Override
public void loadProperties() {
// Ensure that all required properties are present
this.simpleDBConnectionUtils.initializeMissingProperties(this.properties);
removeListeners();
String accountId = this.properties.getProperty(ISimpleDBConnectionProfileConstants.ACCOUNT_ID);
Map<String, String> accounts = AwsToolkitCore.getDefault().getAccountManager().getAllAccountNames();
String accountName = accounts.get(accountId);
this.accountSelection.selectAccountName(accountName);
String endpoint = this.properties.getProperty(ISimpleDBConnectionProfileConstants.ENDPOINT);
if (endpoint != null) {
for (int i = 0; i < this.endpointCombo.getItemCount(); i++) {
String availableEndpoint = (String)this.endpointCombo.getData(this.endpointCombo.getItem(i));
if (endpoint.equals(availableEndpoint)) {
this.endpointCombo.select(i);
}
}
}
initialize();
setConnectionInformation();
}
/**
* @see org.eclipse.datatools.connectivity.ui.wizards.IDriverUIContributor#setDialogPage(org.eclipse.jface.dialogs.DialogPage)
*/
@Override
public void setDialogPage(final DialogPage parentPage) {
this.parentPage = parentPage;
updateErrorMessage();
}
/**
* @see org.eclipse.datatools.connectivity.ui.wizards.IDriverUIContributor#setDriverUIContributorInformation(org.eclipse.datatools.connectivity.ui.wizards.IDriverUIContributorInformation)
*/
@Override
public void setDriverUIContributorInformation(final IDriverUIContributorInformation contributorInformation) {
this.contributorInformation = contributorInformation;
this.properties = contributorInformation.getProperties();
}
/**
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
@Override
public void handleEvent(final Event event) {
if (!this.isReadOnly) {
setConnectionInformation();
updateErrorMessage();
}
}
protected void updateErrorMessage() {
if ( this.parentPage != null && !this.parentPage.getControl().isDisposed()) {
if ( !this.accountValid() ) {
this.parentPage.setErrorMessage("Selected account is not correctly configured");
} else {
this.parentPage.setErrorMessage(null);
}
}
}
private void setConnectionInformation() {
this.properties.setProperty(IJDBCDriverDefinitionConstants.URL_PROP_ID, "jdbc:simpledb"); // avoids DTP asserts //$NON-NLS-1$
this.properties.setProperty(IJDBCDriverDefinitionConstants.DATABASE_NAME_PROP_ID, DATABASE_LABEL);
String endpoint = (String)this.endpointCombo.getData(this.endpointCombo.getText());
this.properties.setProperty(ISimpleDBConnectionProfileConstants.ENDPOINT, endpoint);
String accountId = this.accountSelection.getSelectedAccountId();
this.properties.setProperty(ISimpleDBConnectionProfileConstants.ACCOUNT_ID, accountId);
this.contributorInformation.setProperties(this.properties);
}
private void initialize() {
addListeners();
}
private void addListeners() {
this.endpointCombo.addListener(SWT.Selection, this);
this.accountSelection.addListener(SWT.Selection, this);
}
private void removeListeners() {
this.endpointCombo.removeListener(SWT.Selection, this);
}
}
| 8,014 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/explorer/SimpleDBLabelProviderExtension.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.enablement.simpledb.internal.ui.explorer;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.virtual.IColumnNode;
import org.eclipse.datatools.connectivity.sqm.server.internal.ui.explorer.providers.SQLModelLabelProviderExtension;
import org.eclipse.datatools.modelbase.sql.schema.Database;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import com.amazonaws.eclipse.datatools.enablement.simpledb.internal.ui.Messages;
public class SimpleDBLabelProviderExtension extends SQLModelLabelProviderExtension {
public SimpleDBLabelProviderExtension() {
}
@Override
public String getText(final Object element) {
if (element instanceof IColumnNode) {
IColumnNode node = (IColumnNode) element;
try {
Table table = (Table) node.getParent();
Database db = table.getSchema().getDatabase() == null ? table.getSchema().getCatalog().getDatabase() : table
.getSchema().getDatabase();
if (SimpleDBContentProviderExtension.DB_DEFINITION_VENDOR.equals(db.getVendor())) {
return Messages.itemName_and_attributes;
}
} catch (Exception e) {
// ignore - some other tree
}
}
return super.getText(element);
}
}
| 8,015 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/explorer/SimpleDBContentProviderExtension.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.internal.ui.explorer;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.providers.content.virtual.ColumnNode;
import org.eclipse.datatools.connectivity.sqm.core.internal.ui.explorer.providers.content.virtual.VirtualNodeServiceFactory;
import org.eclipse.datatools.connectivity.sqm.core.ui.explorer.virtual.IVirtualNode;
import org.eclipse.datatools.connectivity.sqm.server.internal.ui.explorer.providers.SQLModelContentProviderExtension;
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;
import org.eclipse.ui.navigator.IPipelinedTreeContentProvider;
import org.eclipse.ui.navigator.PipelinedShapeModification;
import org.eclipse.ui.navigator.PipelinedViewerUpdate;
/**
* This class is a content provider implementation for navigatorContent extensions. This class provides SQL model
* content to the navigator.
*/
public class SimpleDBContentProviderExtension extends SQLModelContentProviderExtension implements
IPipelinedTreeContentProvider {
public static final String DOMAINS = "Domains"; //$NON-NLS-1$
public static final String DB_DEFINITION_VENDOR = "SimpleDB"; //$NON-NLS-1$
public SimpleDBContentProviderExtension() {
super();
}
@Override
public Object[] getChildren(final Object parentElement) {
return new Object[0];
}
@Override
public boolean hasChildren(final Object element) {
return false;
}
@Override
public void getPipelinedChildren(final Object parent, final Set theCurrentChildren) {
}
@Override
public void getPipelinedElements(final Object anInput, final Set theCurrentElements) {
}
@Override
public Object getPipelinedParent(final Object anObject, final Object suggestedParent) {
return suggestedParent;
}
@Override
public boolean interceptRefresh(final PipelinedViewerUpdate refreshSynchronization) {
return false;
}
@Override
public PipelinedShapeModification interceptRemove(final PipelinedShapeModification removeModification) {
return removeModification;
}
@Override
public boolean interceptUpdate(final PipelinedViewerUpdate anUpdateSynchronization) {
return false;
}
@Override
public PipelinedShapeModification interceptAdd(final PipelinedShapeModification anAddModification) {
//anAddModification.getChildren().clear();
if (anAddModification.getParent() instanceof Database
&& DB_DEFINITION_VENDOR.equals(((Database) anAddModification.getParent()).getVendor())) {
try {
Database db = (Database) anAddModification.getParent();
Schema schema = ((Schema) ((Catalog) db.getCatalogs().get(0)).getSchemas().get(0));
anAddModification.getChildren().clear();
IVirtualNode domains = VirtualNodeServiceFactory.INSTANCE.makeTableNode(DOMAINS, DOMAINS, db);
domains.addChildren(schema.getTables());
anAddModification.getChildren().add(domains);
} catch (Exception e) {
// strange broken tree, nothing to mangle
}
}
if (anAddModification.getParent() instanceof Table) {
Iterator it = anAddModification.getChildren().iterator();
while (it.hasNext()) {
Object o = it.next();
if (!(o instanceof ColumnNode)) {
it.remove();
}
}
}
if (anAddModification.getParent() instanceof Column) {
anAddModification.getChildren().clear();
}
return anAddModification;
}
}
| 8,016 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/menu/NewSimpleDBConnectionHandler.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.datatools.enablement.simpledb.internal.ui.menu;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.datatools.connectivity.ui.actions.AddProfileViewAction;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.WorkbenchException;
import com.amazonaws.eclipse.core.AwsToolkitCore;
public class NewSimpleDBConnectionHandler extends AbstractHandler {
/** The ID of the Database Development perspective provided by DTP */
private static final String DATABASE_DEVELOPMENT_PERSPECTIVE_ID =
"org.eclipse.datatools.sqltools.sqleditor.perspectives.EditorPerspective";
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
try {
PlatformUI.getWorkbench().showPerspective(DATABASE_DEVELOPMENT_PERSPECTIVE_ID,
PlatformUI.getWorkbench().getActiveWorkbenchWindow());
new AddProfileViewAction().run();
} catch (WorkbenchException e) {
AwsToolkitCore.getDefault().reportException("Unable to open connection wizard", e);
}
return null;
}
}
| 8,017 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/menu/OpenSyntaxHelpUrlHandler.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.enablement.simpledb.internal.ui.menu;
public class OpenSyntaxHelpUrlHandler extends OpenUrlHandler {
@Override
protected String urlToOpen() {
return "http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/UsingSelect.html"; //$NON-NLS-1$
}
}
| 8,018 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/ui/menu/OpenUrlHandler.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.enablement.simpledb.internal.ui.menu;
import java.net.URL;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
public abstract class OpenUrlHandler extends AbstractHandler {
private String url;
public OpenUrlHandler() {
this.url = urlToOpen();
}
protected abstract String urlToOpen();
@Override
public Object execute(final ExecutionEvent ee) throws ExecutionException {
try {
IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport();
IWebBrowser browser = browserSupport.createBrowser(IWorkbenchBrowserSupport.LOCATION_BAR
| IWorkbenchBrowserSupport.NAVIGATION_BAR, null, null, null);
browser.openURL(new URL(this.url));
} catch (Exception e) {
}
return null;
}
}
| 8,019 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/connection/SimpleDBDatabaseRecognizer.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.internal.connection;
import java.sql.Connection;
import org.eclipse.datatools.connectivity.sqm.core.definition.DatabaseDefinition;
import org.eclipse.datatools.connectivity.sqm.internal.core.definition.DatabaseDefinitionRegistryImpl;
import org.eclipse.datatools.connectivity.sqm.internal.core.definition.IDatabaseRecognizer;
public class SimpleDBDatabaseRecognizer implements IDatabaseRecognizer {
public static final String PRODUCT = "SimpleDB"; //$NON-NLS-1$
public static final String VERSION1 = "1.0"; //$NON-NLS-1$
@Override
public DatabaseDefinition recognize(final Connection connection) {
try {
String product = connection.getMetaData().getDatabaseProductName();
if (product.indexOf(PRODUCT) < 0) {
return null;
}
// String version = connection.getMetaData().getDatabaseProductVersion();
// if (version == null) {
// return null;
// }
//
// Pattern p = Pattern.compile("[\\d]+[.][\\d]+[.][\\d]+"); //$NON-NLS-1$
// Matcher m = p.matcher(version);
// m.find();
// version = m.group();
// if (version.startsWith("1.")) { //$NON-NLS-1$
return DatabaseDefinitionRegistryImpl.INSTANCE.getDefinition(PRODUCT, VERSION1);
// }
} catch (Exception e) {
}
return null;
}
}
| 8,020 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/connection/SimpleDBConnectionFactory.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.internal.connection;
import org.eclipse.datatools.connectivity.IConnection;
import org.eclipse.datatools.connectivity.IConnectionFactory;
import org.eclipse.datatools.connectivity.IConnectionProfile;
import com.amazonaws.eclipse.datatools.enablement.simpledb.connection.SimpleDBConnectionUtils;
public class SimpleDBConnectionFactory implements IConnectionFactory {
/**
* SimpleDB connection utils for listing available endpoints, default
* endpoint, populating missing required connection profile properties,
* etc.
*/
private SimpleDBConnectionUtils simpleDBConnectionUtils = new SimpleDBConnectionUtils();
/**
* @see org.eclipse.datatools.connectivity.IConnectionFactory#createConnection(org.eclipse.datatools.connectivity.IConnectionProfile)
*/
@Override
public IConnection createConnection(final IConnectionProfile profile) {
this.simpleDBConnectionUtils.initializeMissingProperties(profile.getBaseProperties());
SimpleDBConnection connection = new SimpleDBConnection(profile, getClass());
connection.open();
return connection;
}
/**
* @see org.eclipse.datatools.connectivity.IConnectionFactory#createConnection(org.eclipse.datatools.connectivity.IConnectionProfile, java.lang.String, java.lang.String)
*/
@Override
public IConnection createConnection(final IConnectionProfile profile, final String uid, final String pwd) {
return createConnection(profile);
}
}
| 8,021 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/connection/SimpleDBPropertiesPersistenceHook.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.internal.connection;
import java.util.Properties;
import org.eclipse.datatools.connectivity.drivers.jdbc.IJDBCConnectionProfileConstants;
import org.eclipse.datatools.connectivity.drivers.jdbc.JDBCPasswordPropertyPersistenceHook;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.datatools.enablement.simpledb.connection.ISimpleDBConnectionProfileConstants;
public class SimpleDBPropertiesPersistenceHook extends JDBCPasswordPropertyPersistenceHook {
@Override
public String getConnectionPropertiesPageID() {
return "com.amazonaws.eclipse.datatools.enablement.simpledb.profileProperties"; //$NON-NLS-1$
}
@Override
public boolean arePropertiesComplete(final Properties props) {
String uid = props.getProperty(IJDBCConnectionProfileConstants.USERNAME_PROP_ID);
String pwd = props.getProperty(IJDBCConnectionProfileConstants.PASSWORD_PROP_ID);
String accountId = props.getProperty(ISimpleDBConnectionProfileConstants.ACCOUNT_ID);
/*
* Legacy support: only set their user and pass if they hadn't
* explicitly set it before.
*/
if ( uid == null || uid.length() == 0 || pwd == null || pwd.length() == 0 ) {
AccountInfo accountInfo = null;
if ( accountId != null ) {
accountInfo = AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(accountId);
} else {
accountInfo = AwsToolkitCore.getDefault().getAccountInfo();
}
return accountInfo.isValid();
}
return persistPassword(props) || props.getProperty(IJDBCConnectionProfileConstants.PASSWORD_PROP_ID, null) != null;
}
}
| 8,022 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/connection/SimpleDBConnection.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.internal.connection;
import java.sql.Driver;
import java.util.Properties;
import org.eclipse.datatools.connectivity.IConnectionProfile;
import org.eclipse.datatools.connectivity.drivers.IDriverMgmtConstants;
import org.eclipse.datatools.connectivity.drivers.jdbc.IJDBCConnectionProfileConstants;
import org.eclipse.datatools.connectivity.drivers.jdbc.JDBCConnection;
import org.eclipse.datatools.connectivity.internal.ConnectivityPlugin;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.datatools.enablement.simpledb.connection.ISimpleDBConnectionProfileConstants;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.JdbcDriver;
public class SimpleDBConnection extends JDBCConnection {
private boolean mHasDriver = true;
public SimpleDBConnection(final IConnectionProfile profile, final Class<?> factoryClass) {
super(profile, factoryClass);
}
@Override
public void open() {
if (this.mConnection != null) {
close();
}
this.mConnection = null;
this.mConnectException = null;
boolean hasDriver = false;
try {
if (getDriverDefinition() != null) {
hasDriver = true;
// super.open();
if (this.mConnection != null) {
close();
}
this.mConnection = null;
this.mConnectException = null;
internalCreateConnection();
}
} catch (Exception e) {
if (e.getMessage().equalsIgnoreCase(
ConnectivityPlugin.getDefault().getResourceString("DriverConnectionBase.error.driverDefinitionNotSpecified"))) //$NON-NLS-1$
{
if (profileHasDriverDetails()) {
this.mHasDriver = false;
} else {
e.printStackTrace();
}
} else {
e.printStackTrace();
}
}
if (!hasDriver) {
internalCreateConnection();
}
}
private void internalCreateConnection() {
try {
ClassLoader parentCL = getParentClassLoader();
ClassLoader driverCL = createClassLoader(parentCL);
this.mConnection = createConnection(driverCL);
if (this.mConnection == null) {
// Connect attempt failed without throwing an exception.
// We'll generate one for them.
throw new Exception(ConnectivityPlugin.getDefault().getResourceString("DriverConnectionBase.error.unknown")); //$NON-NLS-1$
}
initVersions();
updateVersionCache();
} catch (Throwable t) {
this.mConnectException = t;
clearVersionCache();
}
}
private boolean profileHasDriverDetails() {
Properties props = getConnectionProfile().getBaseProperties();
String driverClass = props.getProperty(IJDBCConnectionProfileConstants.DRIVER_CLASS_PROP_ID);
String jarList = props.getProperty(IDriverMgmtConstants.PROP_DEFN_JARLIST);
if (driverClass != null && jarList != null) {
return true;
}
return false;
}
@Override
protected Object createConnection(final ClassLoader cl) throws Throwable {
Properties props = getConnectionProfile().getBaseProperties();
Properties connectionProps = new Properties();
String connectURL = props.getProperty(IJDBCConnectionProfileConstants.URL_PROP_ID);
String uid = props.getProperty(IJDBCConnectionProfileConstants.USERNAME_PROP_ID);
String pwd = props.getProperty(IJDBCConnectionProfileConstants.PASSWORD_PROP_ID);
String nameValuePairs = props.getProperty(IJDBCConnectionProfileConstants.CONNECTION_PROPERTIES_PROP_ID);
String endpoint = props.getProperty(ISimpleDBConnectionProfileConstants.ENDPOINT);
String accountId = props.getProperty(ISimpleDBConnectionProfileConstants.ACCOUNT_ID);
String propDelim = ","; //$NON-NLS-1$
/*
* Legacy support: only set their user and pass if they hadn't
* explicitly set it before.
*/
if ( uid == null || uid.length() == 0 || pwd == null || pwd.length() == 0 ) {
AccountInfo accountInfo = null;
if ( accountId != null ) {
accountInfo = AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(accountId);
} else {
// Equivalent to useGlobal legacy property
accountInfo = AwsToolkitCore.getDefault().getAccountInfo();
}
uid = accountInfo.getAccessKey();
pwd = accountInfo.getSecretKey();
}
if (uid != null) {
connectionProps.setProperty("user", uid); //$NON-NLS-1$
}
if (pwd != null) {
connectionProps.setProperty("password", pwd); //$NON-NLS-1$
}
if (endpoint != null) {
connectionProps.setProperty("endpoint", endpoint); //$NON-NLS-1$
}
if (nameValuePairs != null && nameValuePairs.length() > 0) {
String[] pairs = parseString(nameValuePairs, ","); //$NON-NLS-1$
String addPairs = ""; //$NON-NLS-1$
for (int i = 0; i < pairs.length; i++) {
String[] namevalue = parseString(pairs[i], "="); //$NON-NLS-1$
connectionProps.setProperty(namevalue[0], namevalue[1]);
if (i == 0 || i < pairs.length - 1) {
addPairs = addPairs + propDelim;
}
addPairs = addPairs + pairs[i];
}
}
Driver jdbcDriver = new JdbcDriver(com.amazonaws.services.simpledb.AmazonSimpleDBClient.class);
return jdbcDriver.connect(connectURL, connectionProps);
}
}
| 8,023 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/ListDomainsStatement.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.internal.driver;
import java.sql.SQLException;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.JdbcConnection;
import com.amazonaws.services.simpledb.model.ListDomainsRequest;
import com.amazonaws.services.simpledb.model.ListDomainsResult;
/**
* Fetches domain names from the Amazon SimpleDB belonging to the logged in user.
*/
public class ListDomainsStatement extends JdbcPreparedStatement {
public ListDomainsStatement(final JdbcConnection conn, final String sql) {
super(conn, sql);
}
/*
* Collect as many items as SimpleDB allows and return the NextToken, which
* is used to continue the query in a subsequent call to SimpleDB.
*/
@Override
ExecutionResult execute(final String queryText, final int startingRow, final int maxRows, final int requestSize,
final String nextToken) throws SQLException {
ListDomainsRequest request = new ListDomainsRequest();
if (maxRows > 0) {
request.setMaxNumberOfDomains(Math.min(maxRows, 100));
}
if (nextToken != null) {
request.setNextToken(nextToken);
}
ListDomainsResult queryResult;
try {
queryResult = this.conn.getClient().listDomains(request);
} catch (Exception e) {
throw wrapIntoSqlException(e);
}
String domainFilter = null;
int pos = this.sql.lastIndexOf('\'');
if (pos >= 0) {
int pos2 = this.sql.lastIndexOf('\'', pos - 1);
if (pos2 >= 0) {
domainFilter = this.sql.substring(pos2 + 1, pos);
if ("%".equals(domainFilter)) { //$NON-NLS-1$
domainFilter = null;
}
}
}
int row = startingRow;
for (String domain : queryResult.getDomainNames()) {
if (this.cancel) {
break;
}
if (domainFilter != null && !domain.equalsIgnoreCase(domainFilter)) {
continue;
}
// * <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
// * <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
// * <LI><B>TABLE_NAME</B> String => table name
// * <LI><B>TABLE_TYPE</B> String => table type. Typical types are "TABLE",
// * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY",
// * "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
// * <LI><B>REMARKS</B> String => explanatory comment on the table
// * <LI><B>TYPE_CAT</B> String => the types catalog (may be <code>null</code>)
// * <LI><B>TYPE_SCHEM</B> String => the types schema (may be <code>null</code>)
// * <LI><B>TYPE_NAME</B> String => type name (may be <code>null</code>)
// * <LI><B>SELF_REFERENCING_COL_NAME</B> String => name of the designated
// * "identifier" column of a typed table (may be <code>null</code>)
// * <LI><B>REF_GENERATION</B> String => specifies how values in
// * SELF_REFERENCING_COL_NAME are created. Values are
// * "SYSTEM", "USER", "DERIVED". (may be <code>null</code>)
// * </OL>
this.data.add("TABLE_CAT", "", row); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("TABLE_SCHEM", "", row); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("TABLE_NAME", domain, row); //$NON-NLS-1$
this.data.add("TABLE_TYPE", "TABLE", row); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("REMARKS", null, row); //$NON-NLS-1$
this.data.add("TYPE_CAT", null, row); //$NON-NLS-1$
this.data.add("TYPE_SCHEM", null, row); //$NON-NLS-1$
this.data.add("TYPE_NAME", null, row); //$NON-NLS-1$
this.data.add("SELF_REFERENCING_COL_NAME", null, row); //$NON-NLS-1$
this.data.add("REF_GENERATION", "USER", row); //$NON-NLS-1$ //$NON-NLS-2$
row++;
}
return new ExecutionResult(queryResult.getNextToken(), row - startingRow);
}
}
| 8,024 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcResultSet.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.internal.driver;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.SimpleDBItemName;
import com.ibm.icu.text.SimpleDateFormat;
/**
* JDBC ResultSet implementation for the Amazon SimpleDB. Wraps around a simple raw data received from the SDB request.
*/
public class JdbcResultSet implements ResultSet, ResultSetMetaData {
private final JdbcStatement stmt;
private boolean open = false; // true means have results and can iterate them
private int row = 0; // number of current row, starts at 1
private int lastCol; // last column accessed, for wasNull(). -1 if none
SQLWarning warning = null;
public JdbcResultSet(final JdbcStatement stmt) {
this.stmt = stmt;
}
@Override
public void clearWarnings() throws SQLException {
this.warning = null;
}
@Override
public SQLWarning getWarnings() throws SQLException {
return this.warning;
}
@Override
public void close() throws SQLException {
this.open = false;
this.row = 0;
this.lastCol = -1;
}
public void open() {
this.open = true;
}
public boolean isOpen() {
return this.open;
}
/* Throws SQLException if ResultSet is not open. */
void assertOpen() throws SQLException {
if (!this.open) {
throw new SQLException("ResultSet closed"); //$NON-NLS-1$
}
}
@Override
public String getCursorName() throws SQLException {
return null;
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return this;
}
@Override
public Statement getStatement() throws SQLException {
return this.stmt;
}
@Override
public int findColumn(final String columnName) throws SQLException {
assertOpen();
return this.stmt.data.findAttribute(columnName) + 1;
}
private int toNativeCol(int col) throws SQLException {
// if (colsMeta == null) {
// throw new IllegalStateException("SDB JDBC: inconsistent internal state");
// }
// if (col < 1 || col > colsMeta.length) {
// throw new SQLException("column " + col + " out of bounds [1," + colsMeta.length + "]");
// }
return --col;
}
@Override
public int getRow() throws SQLException {
return this.row;
}
@Override
public boolean next() throws SQLException {
if (!this.open || this.stmt == null) {
return false;
}
this.lastCol = -1;
this.row++;
// check if we are row limited by the statement or the ResultSet
if (this.stmt.getMaxRows() != 0 && this.row > this.stmt.getMaxRows()) {
return false;
}
if (this.row > this.stmt.data.getRowNum()) {
close();
return false;
}
return true;
}
@Override
public boolean rowDeleted() throws SQLException {
return false;
}
@Override
public boolean rowInserted() throws SQLException {
return false;
}
@Override
public boolean rowUpdated() throws SQLException {
return false;
}
@Override
public boolean wasNull() throws SQLException {
return this.lastCol > 0 && getString(this.lastCol) == null; // simple impl, but might work
}
@Override
public int getType() throws SQLException {
return TYPE_FORWARD_ONLY;
}
@Override
public int getFetchSize() throws SQLException {
return 0;
}
@Override
public void setFetchSize(final int rows) throws SQLException {
// if (0 > rows || (this.stmt.getMaxRows() != 0 && rows > this.stmt.getMaxRows())) {
// throw new SQLException("fetch size " + rows + " out of bounds " + this.stmt.getMaxRows());
// }
}
@Override
public int getFetchDirection() throws SQLException {
assertOpen();
return ResultSet.FETCH_FORWARD;
}
@Override
public void setFetchDirection(final int d) throws SQLException {
assertOpen();
if (d != ResultSet.FETCH_FORWARD) {
throw new SQLException("only FETCH_FORWARD direction supported"); //$NON-NLS-1$
}
}
@Override
public boolean isAfterLast() throws SQLException {
return !this.open;
}
@Override
public boolean isBeforeFirst() throws SQLException {
return this.open && this.row == 0;
}
@Override
public boolean isFirst() throws SQLException {
return this.row == 1;
}
@Override
public boolean isLast() throws SQLException {
return this.stmt.data.getRowNum() == this.row;
}
@Override
public int getConcurrency() throws SQLException {
return CONCUR_READ_ONLY;
}
// DATA ACCESS FUNCTIONS ////////////////////////////////////////
@Override
public boolean getBoolean(final int col) throws SQLException {
return getInt(col) == 0 ? false : true;
}
@Override
public boolean getBoolean(final String col) throws SQLException {
return getBoolean(findColumn(col));
}
@Override
public byte getByte(final int col) throws SQLException {
return (byte) getInt(col);
}
@Override
public byte getByte(final String col) throws SQLException {
return getByte(findColumn(col));
}
@Override
public byte[] getBytes(final int col) throws SQLException {
return getString(col).getBytes();
}
@Override
public byte[] getBytes(final String col) throws SQLException {
return getBytes(findColumn(col));
}
@Override
public Date getDate(final int col) throws SQLException {
try {
String str = getString(col);
if (str == null) {
return null;
}
return new Date(new SimpleDateFormat().parse(str).getTime());
} catch (Exception e) {
throw new SQLException(e.getMessage());
}
}
@Override
public Date getDate(final int col, final Calendar cal) throws SQLException {
if (cal == null) {
return getDate(col);
}
try {
String str = getString(col);
if (str == null) {
return null;
}
cal.setTimeInMillis(new SimpleDateFormat().parse(str).getTime());
return new Date(cal.getTime().getTime());
} catch (Exception e) {
throw new SQLException(e.getMessage());
}
}
@Override
public Date getDate(final String col) throws SQLException {
return getDate(findColumn(col), Calendar.getInstance());
}
@Override
public Date getDate(final String col, final Calendar cal) throws SQLException {
return getDate(findColumn(col), cal);
}
@Override
public double getDouble(final int col) throws SQLException {
String str = getString(col);
if (str == null) {
return 0d;
}
return Double.parseDouble(str);
}
@Override
public double getDouble(final String col) throws SQLException {
return getDouble(findColumn(col));
}
@Override
public float getFloat(final int col) throws SQLException {
String str = getString(col);
if (str == null) {
return 0f;
}
return Float.parseFloat(str);
}
@Override
public float getFloat(final String col) throws SQLException {
return getFloat(findColumn(col));
}
@Override
public int getInt(final int col) throws SQLException {
String str = getString(col);
if (str == null) {
return 0;
}
return Integer.parseInt(str);
}
@Override
public int getInt(final String col) throws SQLException {
return getInt(findColumn(col));
}
@Override
public long getLong(final int col) throws SQLException {
String str = getString(col);
if (str == null) {
return 0;
}
return Long.parseLong(str);
}
@Override
public long getLong(final String col) throws SQLException {
return getLong(findColumn(col));
}
@Override
public short getShort(final int col) throws SQLException {
return (short) getInt(col);
}
@Override
public short getShort(final String col) throws SQLException {
return getShort(findColumn(col));
}
@Override
public String getString(final int col) throws SQLException {
this.lastCol = col;
return this.stmt.data.getString(this.row - 1, col - 1, ","); //$NON-NLS-1$
}
@Override
public String getString(final String col) throws SQLException {
return getString(findColumn(col));
}
@Override
public Time getTime(final int col) throws SQLException {
try {
String str = getString(col);
if (str == null) {
return null;
}
return new Time(new SimpleDateFormat().parse(str).getTime());
} catch (Exception e) {
throw new SQLException(e.getMessage());
}
}
@Override
public Time getTime(final int col, final Calendar cal) throws SQLException {
if (cal == null) {
return getTime(col);
}
try {
String str = getString(col);
if (str == null) {
return null;
}
cal.setTimeInMillis(new SimpleDateFormat().parse(str).getTime());
return new Time(cal.getTime().getTime());
} catch (Exception e) {
throw new SQLException(e.getMessage());
}
}
@Override
public Time getTime(final String col) throws SQLException {
return getTime(findColumn(col));
}
@Override
public Time getTime(final String col, final Calendar cal) throws SQLException {
return getTime(findColumn(col), cal);
}
@Override
public Timestamp getTimestamp(final int col) throws SQLException {
try {
String str = getString(col);
if (str == null) {
return null;
}
return new Timestamp(new SimpleDateFormat().parse(str).getTime());
} catch (Exception e) {
throw new SQLException(e.getMessage());
}
}
@Override
public Timestamp getTimestamp(final int col, final Calendar cal) throws SQLException {
if (cal == null) {
return getTimestamp(col);
}
try {
String str = getString(col);
if (str == null) {
return null;
}
cal.setTimeInMillis(new SimpleDateFormat().parse(str).getTime());
return new Timestamp(cal.getTime().getTime());
} catch (Exception e) {
throw new SQLException(e.getMessage());
}
}
@Override
public Timestamp getTimestamp(final String col) throws SQLException {
return getTimestamp(findColumn(col));
}
@Override
public Timestamp getTimestamp(final String c, final Calendar ca) throws SQLException {
return getTimestamp(findColumn(c), ca);
}
@Override
public Object getObject(final int col) throws SQLException {
try {
this.lastCol = col;
List<String> obj = this.stmt.data.get(this.row - 1, col - 1);
if (this.stmt.data.isItemNameColumn(this.row - 1, col - 1)) {
return new SimpleDBItemName(obj != null && !obj.isEmpty() ? obj.get(0) : null, true); // ItemName
} else if (obj == null) {
return null;
} else if (obj.size() == 1) {
return obj.get(0); // single value
} else {
return new ArrayList<>(obj); // multi-value
}
} catch (Exception e) {
return null;
}
// TODO check type somehow?
// switch (type) {
// case INTEGER:
// long val = getLong(col);
// if (val > (long) Integer.MAX_VALUE || val < (long) Integer.MIN_VALUE) {
// return new Long(val);
// } else {
// return new Integer((int) val);
// }
// case FLOAT:
// return new Double(getDouble(col));
// case BLOB:
// return getBytes(col);
// default:
// return getString(col);
// }
}
@Override
public Object getObject(final String col) throws SQLException {
return getObject(findColumn(col));
}
// METADATA /////////////////////////////////////////////////////////////////
@Override
public String getCatalogName(final int column) throws SQLException {
return getColumnName(column);
}
@Override
public String getColumnClassName(final int column) throws SQLException {
toNativeCol(column);
return "java.lang.String"; //$NON-NLS-1$
}
@Override
public int getColumnCount() throws SQLException {
toNativeCol(1);
return this.stmt.data.getColumnNum();
}
@Override
public int getColumnDisplaySize(final int column) throws SQLException {
return Integer.MAX_VALUE;
}
@Override
public String getColumnLabel(final int column) throws SQLException {
return getColumnName(column);
}
@Override
public String getColumnName(final int column) throws SQLException {
toNativeCol(column);
return this.stmt.data.getAttributes().get(column - 1);
}
@Override
public int getColumnType(final int column) throws SQLException {
toNativeCol(column);
return this.stmt.data.isItemNameColumn(this.row - 1, column - 1) ? Types.OTHER : Types.VARCHAR;
}
@Override
public String getColumnTypeName(final int column) throws SQLException {
toNativeCol(column);
return this.stmt.data.isItemNameColumn(this.row - 1, column - 1) ? "TEXTID" : "TEXT"; //$NON-NLS-1$ //$NON-NLS-2$
}
@Override
public int getPrecision(final int column) throws SQLException {
return 0;
}
@Override
public int getScale(final int column) throws SQLException {
return 0;
}
@Override
public String getSchemaName(final int column) throws SQLException {
return null;
}
@Override
public String getTableName(final int column) throws SQLException {
return this.stmt.getDomainName();
}
@Override
public boolean isAutoIncrement(final int column) throws SQLException {
return false;
}
@Override
public boolean isCaseSensitive(final int column) throws SQLException {
return true;
}
@Override
public boolean isCurrency(final int column) throws SQLException {
return false;
}
@Override
public boolean isDefinitelyWritable(final int column) throws SQLException {
return true;
}
@Override
public int isNullable(final int column) throws SQLException {
return this.stmt.data.isItemNameColumn(this.row - 1, column - 1) ? columnNoNulls : columnNullable;
}
@Override
public boolean isReadOnly(final int column) throws SQLException {
return false;
}
@Override
public boolean isSearchable(final int column) throws SQLException {
return true;
}
@Override
public boolean isSigned(final int column) throws SQLException {
return false;
}
@Override
public boolean isWritable(final int column) throws SQLException {
return true;
}
// NOT SUPPORTED ////////////////////////////////////////////////////////////
@Override
public Array getArray(final int i) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Array getArray(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public InputStream getAsciiStream(final int col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public InputStream getAsciiStream(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public BigDecimal getBigDecimal(final int col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public BigDecimal getBigDecimal(final int col, final int s) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public BigDecimal getBigDecimal(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public BigDecimal getBigDecimal(final String col, final int s) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public InputStream getBinaryStream(final int col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public InputStream getBinaryStream(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Blob getBlob(final int col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Blob getBlob(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Reader getCharacterStream(final int col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Reader getCharacterStream(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Clob getClob(final int col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Clob getClob(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Object getObject(final int col, final Map<String, Class<?>> map) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Object getObject(final String col, final Map<String, Class<?>> map) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Ref getRef(final int i) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public Ref getRef(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public InputStream getUnicodeStream(final int col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public InputStream getUnicodeStream(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public URL getURL(final int col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public URL getURL(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void insertRow() throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public void moveToCurrentRow() throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public void moveToInsertRow() throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public boolean last() throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public boolean previous() throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public boolean relative(final int rows) throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public boolean absolute(final int row) throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public void afterLast() throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public void beforeFirst() throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public boolean first() throws SQLException {
throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); //$NON-NLS-1$
}
@Override
public void cancelRowUpdates() throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void deleteRow() throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateArray(final int col, final Array x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateArray(final String col, final Array x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateAsciiStream(final int col, final InputStream x, final int l) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateAsciiStream(final String col, final InputStream x, final int l) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBigDecimal(final int col, final BigDecimal x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBigDecimal(final String col, final BigDecimal x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBinaryStream(final int c, final InputStream x, final int l) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBinaryStream(final String c, final InputStream x, final int l) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBlob(final int col, final Blob x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBlob(final String col, final Blob x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBoolean(final int col, final boolean x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBoolean(final String col, final boolean x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateByte(final int col, final byte x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateByte(final String col, final byte x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBytes(final int col, final byte[] x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateBytes(final String col, final byte[] x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateCharacterStream(final int c, final Reader x, final int l) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateCharacterStream(final String c, final Reader r, final int l) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateClob(final int col, final Clob x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateClob(final String col, final Clob x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateDate(final int col, final Date x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateDate(final String col, final Date x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateDouble(final int col, final double x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateDouble(final String col, final double x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateFloat(final int col, final float x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateFloat(final String col, final float x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateInt(final int col, final int x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateInt(final String col, final int x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateLong(final int col, final long x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateLong(final String col, final long x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateNull(final int col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateNull(final String col) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateObject(final int c, final Object x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateObject(final int c, final Object x, final int s) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateObject(final String col, final Object x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateObject(final String c, final Object x, final int s) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateRef(final int col, final Ref x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateRef(final String c, final Ref x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateRow() throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateShort(final int c, final short x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateShort(final String c, final short x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateString(final int c, final String x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateString(final String c, final String x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateTime(final int c, final Time x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateTime(final String c, final Time x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateTimestamp(final int c, final Timestamp x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void updateTimestamp(final String c, final Timestamp x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void refreshRow() throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Reader getNCharacterStream(final int arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Reader getNCharacterStream(final String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public NClob getNClob(final int arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public NClob getNClob(final String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getNString(final int arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getNString(final String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public RowId getRowId(final int arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public RowId getRowId(final String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLXML getSQLXML(final int arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLXML getSQLXML(final String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void updateAsciiStream(final int arg0, final InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateAsciiStream(final String arg0, final InputStream arg1)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateAsciiStream(final int arg0, final InputStream arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateAsciiStream(final String arg0, final InputStream arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(final int arg0, final InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(final String arg0, final InputStream arg1)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(final int arg0, final InputStream arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(final String arg0, final InputStream arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(final int arg0, final InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(final String arg0, final InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(final int arg0, final InputStream arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(final String arg0, final InputStream arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(final int arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(final String arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(final int arg0, final Reader arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(final String arg0, final Reader arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(final int arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(final String arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(final int arg0, final Reader arg1, final long arg2) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(final String arg0, final Reader arg1, final long arg2) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNCharacterStream(final int arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNCharacterStream(final String arg0, final Reader arg1)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNCharacterStream(final int arg0, final Reader arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNCharacterStream(final String arg0, final Reader arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(final int arg0, final NClob arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(final String arg0, final NClob arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(final int arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(final String arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(final int arg0, final Reader arg1, final long arg2) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(final String arg0, final Reader arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNString(final int arg0, final String arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNString(final String arg0, final String arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateRowId(final int arg0, final RowId arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateRowId(final String arg0, final RowId arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateSQLXML(final int arg0, final SQLXML arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateSQLXML(final String arg0, final SQLXML arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isWrapperFor(final Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(final Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
return null;
}
@Override
public <T> T getObject(String columnLabel, Class<T> type)
throws SQLException {
return null;
}
}
| 8,025 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/ListAttributesStatement.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.internal.driver;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.JdbcConnection;
/**
* Fetches domain attributes for the given domain from the Amazon SimpleDB.
*/
public class ListAttributesStatement extends JdbcPreparedStatement {
public ListAttributesStatement(final JdbcConnection conn, final String sql) {
super(conn, sql);
}
/*
Each column description has the following columns:
TABLE_CAT String => table catalog (may be null)
TABLE_SCHEM String => table schema (may be null)
TABLE_NAME String => table name
COLUMN_NAME String => column name
DATA_TYPE int => SQL type from java.sql.Types
TYPE_NAME String => Data source dependent type name, for a UDT the type name is fully qualified
COLUMN_SIZE int => column size. For char or date types this is the maximum number of characters, for numeric or decimal types this is precision.
BUFFER_LENGTH is not used.
DECIMAL_DIGITS int => the number of fractional digits
NUM_PREC_RADIX int => Radix (typically either 10 or 2)
NULLABLE int => is NULL allowed.
columnNoNulls - might not allow NULL values
columnNullable - definitely allows NULL values
columnNullableUnknown - nullability unknown
REMARKS String => comment describing column (may be null)
COLUMN_DEF String => default value (may be null)
SQL_DATA_TYPE int => unused
SQL_DATETIME_SUB int => unused
CHAR_OCTET_LENGTH int => for char types the maximum number of bytes in the column
ORDINAL_POSITION int => index of column in table (starting at 1)
IS_NULLABLE String => "NO" means column definitely does not allow NULL values; "YES" means the column might allow NULL values. An empty string means nobody knows.
SCOPE_CATLOG String => catalog of table that is the scope of a reference attribute (null if DATA_TYPE isn't REF)
SCOPE_SCHEMA String => schema of table that is the scope of a reference attribute (null if the DATA_TYPE isn't REF)
SCOPE_TABLE String => table name that this the scope of a reference attribure (null if the DATA_TYPE isn't REF)
SOURCE_DATA_TYPE short => source type of a distinct type or user-generated Ref type, SQL type from java.sql.Types (null if DATA_TYPE isn't DISTINCT or user-generated REF)
*/
@Override
ExecutionResult execute(final String queryText, final int startingRow, final int maxRows, final int requestSize,
final String nextToken) throws SQLException {
super.execute(queryText, startingRow, maxRows, requestSize, nextToken);
ArrayList<String> attrs = new ArrayList<>(this.data.getAttributes());
int itemNameColumn = -1;
if (attrs.size() > 0) { // there was something in the domain
itemNameColumn = this.data.getItemNameColumn(0);
}
this.data = new RawData();
// to avoid attr order change on new value appearance, which breaks open editors' table structure
String itemName = null;
if (itemNameColumn >= 0) {
itemName = attrs.remove(itemNameColumn);
}
Collections.sort(attrs);
if (itemNameColumn >= 0) {
attrs.add(itemNameColumn, itemName);
}
String domainName = getDomainName();
for (int i = 0; i < attrs.size(); i++) {
addColumnData(domainName, attrs.get(i), i == itemNameColumn, i);
}
// If no attributes were returned, we still want to report itemName()
// otherwise we'll cause an error when opening the TableData editor.
if (attrs.size() == 0) {
addColumnData(domainName, "itemName()", true, 0);
}
return new ExecutionResult(null, attrs.size());
}
private void addColumnData(final String domainName, final String columnName, final boolean isItemNameAttribute, final int columnNumber) {
this.data.add("TABLE_CAT", "", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("TABLE_SCHEM", "", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("TABLE_NAME", domainName, columnNumber); //$NON-NLS-1$
this.data.add("COLUMN_NAME", columnName, columnNumber); //$NON-NLS-1$
this.data.add("DATA_TYPE", "12", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("TYPE_NAME", isItemNameAttribute ? "TEXTID" : "TEXT", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
this.data.add("COLUMN_SIZE", "1024", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("BUFFER_LENGTH", "1024", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("DECIMAL_DIGITS", "10", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("NUM_PREC_RADIX", "10", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("NULLABLE", isItemNameAttribute ? "0" : "1", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
this.data.add("REMARKS", null, columnNumber); //$NON-NLS-1$
this.data.add("COLUMN_DEF", null, columnNumber); //$NON-NLS-1$
this.data.add("SQL_DATA_TYPE", "0", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("SQL_DATETIME_SUB", "0", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("CHAR_OCTET_LENGTH", "1024", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("ORDINAL_POSITION", "" + (columnNumber + 1), columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("IS_NULLABLE", "Y", columnNumber); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("SCOPE_CATLOG", null, columnNumber); //$NON-NLS-1$
this.data.add("SCOPE_SCHEMA", null, columnNumber); //$NON-NLS-1$
this.data.add("SCOPE_TABLE", null, columnNumber); //$NON-NLS-1$
this.data.add("SOURCE_DATA_TYPE", null, columnNumber); //$NON-NLS-1$
}
}
| 8,026 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcDatabaseMetaData.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.internal.driver;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.RowIdLifetime;
import java.sql.SQLException;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.JdbcConnection;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.SimpleDBItemName;
/**
* SDB JDBC metadata wrapper. Provides domains and attributes and all other
* database properties. For metadata queries creates specific JDBC statements
* which are transformed later into requests through the Amazon SDB client, see
* {@link JdbcStatement}.
*/
public class JdbcDatabaseMetaData implements DatabaseMetaData {
private JdbcConnection conn;
private PreparedStatement getTables = null, getColumns = null,
getTableTypes = null, getTypeInfo = null, getCrossReference = null,
getCatalogs = null, getSchemas = null, getUDTs = null,
getColumnsTblName = null, getSuperTypes = null,
getSuperTables = null, getTablePrivileges = null,
getExportedKeys = null, getPrimaryKeys = null,
getProcedures = null, getProcedureColumns = null,
getAttributes = null, getBestRowIdentifier = null,
getVersionColumns = null, getColumnPrivileges = null;
/** Used by PrepStmt to save generating a new statement every call. */
private PreparedStatement getGeneratedKeys = null;
public JdbcDatabaseMetaData(final JdbcConnection connection) {
this.conn = connection;
}
void checkOpen() throws SQLException {
if (this.conn == null) {
throw new SQLException("connection closed"); //$NON-NLS-1$
}
}
synchronized void close() throws SQLException {
if (this.conn == null) {
return;
}
try {
if (this.getTables != null) {
this.getTables.close();
}
if (this.getColumns != null) {
this.getColumns.close();
}
if (this.getTableTypes != null) {
this.getTableTypes.close();
}
if (this.getTypeInfo != null) {
this.getTypeInfo.close();
}
if (this.getCrossReference != null) {
this.getCrossReference.close();
}
if (this.getCatalogs != null) {
this.getCatalogs.close();
}
if (this.getSchemas != null) {
this.getSchemas.close();
}
if (this.getUDTs != null) {
this.getUDTs.close();
}
if (this.getColumnsTblName != null) {
this.getColumnsTblName.close();
}
if (this.getSuperTypes != null) {
this.getSuperTypes.close();
}
if (this.getSuperTables != null) {
this.getSuperTables.close();
}
if (this.getTablePrivileges != null) {
this.getTablePrivileges.close();
}
if (this.getExportedKeys != null) {
this.getExportedKeys.close();
}
if (this.getPrimaryKeys != null) {
this.getPrimaryKeys.close();
}
if (this.getProcedures != null) {
this.getProcedures.close();
}
if (this.getProcedureColumns != null) {
this.getProcedureColumns.close();
}
if (this.getAttributes != null) {
this.getAttributes.close();
}
if (this.getBestRowIdentifier != null) {
this.getBestRowIdentifier.close();
}
if (this.getVersionColumns != null) {
this.getVersionColumns.close();
}
if (this.getColumnPrivileges != null) {
this.getColumnPrivileges.close();
}
if (this.getGeneratedKeys != null) {
this.getGeneratedKeys.close();
}
this.getTables = null;
this.getColumns = null;
this.getTableTypes = null;
this.getTypeInfo = null;
this.getCrossReference = null;
this.getCatalogs = null;
this.getSchemas = null;
this.getUDTs = null;
this.getColumnsTblName = null;
this.getSuperTypes = null;
this.getSuperTables = null;
this.getTablePrivileges = null;
this.getExportedKeys = null;
this.getPrimaryKeys = null;
this.getProcedures = null;
this.getProcedureColumns = null;
this.getAttributes = null;
this.getBestRowIdentifier = null;
this.getVersionColumns = null;
this.getColumnPrivileges = null;
this.getGeneratedKeys = null;
} finally {
this.conn = null;
}
}
@Override
public ResultSet getAttributes(final String catalog,
final String schemaPattern, final String typeNamePattern,
final String attributeNamePattern) throws SQLException {
// XXX
return new JdbcResultSet(null);
}
@Override
public ResultSet getBestRowIdentifier(final String catalog,
final String schema, final String table, final int scope,
final boolean nullable) throws SQLException {
return new JdbcResultSet(null);
// throw new SQLException("not supported: bestRowIdentifier");
}
@Override
public ResultSet getCatalogs() throws SQLException {
if (this.getCatalogs == null) {
this.getCatalogs = new JdbcPreparedStatement(this.conn,
"select null as TABLE_CAT") { //$NON-NLS-1$
@Override
ExecutionResult execute(final String queryText,
final int startingRow, final int maxRows,
final int requestSize, final String nextToken)
throws SQLException {
this.data.add("TABLE_CAT", "", 0); //$NON-NLS-1$ //$NON-NLS-2$
return new ExecutionResult(null, 1);
}
};
}
this.getCatalogs.clearParameters();
return this.getCatalogs.executeQuery();
}
@Override
public ResultSet getColumnPrivileges(final String catalog,
final String schema, final String table,
final String columnNamePattern) throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getColumns(final String catalog,
final String schemaPattern, final String tableNamePattern,
final String columnNamePattern) throws SQLException {
if (this.getColumns == null) {
this.getColumns = new ListAttributesStatement(this.conn, null);
}
this.getColumns.clearParameters();
if (tableNamePattern == null || tableNamePattern.length() == 0) {
return new JdbcResultSet(null);
}
return this.getColumns
.executeQuery("select * from " + JdbcStatement.DELIMITED_IDENTIFIER_QUOTE + tableNamePattern //$NON-NLS-1$
+ JdbcStatement.DELIMITED_IDENTIFIER_QUOTE
+ " limit 10"); //$NON-NLS-1$
}
@Override
public ResultSet getCrossReference(final String primaryCatalog,
final String primarySchema, final String primaryTable,
final String foreignCatalog, final String foreignSchema,
final String foreignTable) throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getExportedKeys(final String catalog, final String schema,
final String table) throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getImportedKeys(final String catalog, final String schema,
final String table) throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getIndexInfo(final String catalog, final String schema,
final String table, final boolean unique, final boolean approximate)
throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getPrimaryKeys(final String catalog, final String schema,
final String table) throws SQLException {
if (this.getPrimaryKeys == null) {
this.getPrimaryKeys = new JdbcPreparedStatement(this.conn,
"select null") { //$NON-NLS-1$
@Override
ExecutionResult execute(final String queryText,
final int startingRow, final int maxRows,
final int requestSize, final String nextToken)
throws SQLException {
this.data.add("TABLE_CAT", catalog, 0); //$NON-NLS-1$
this.data.add("TABLE_SCHEM", schema, 0); //$NON-NLS-1$
this.data.add("TABLE_NAME", table, 0); //$NON-NLS-1$
this.data.add(
"COLUMN_NAME", SimpleDBItemName.ITEM_HEADER, 0); //$NON-NLS-1$
this.data.add("KEY_SEQ", "0", 0); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("PK_NAME", null, 0); //$NON-NLS-1$
return new ExecutionResult(null, 1);
}
};
}
this.getPrimaryKeys.clearParameters();
return this.getPrimaryKeys.executeQuery();
}
@Override
public ResultSet getProcedureColumns(final String catalog,
final String schemaPattern, final String procedureNamePattern,
final String columnNamePattern) throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getProcedures(final String catalog,
final String schemaPattern, final String procedureNamePattern)
throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getSchemas() throws SQLException {
if (this.getSchemas == null) {
this.getSchemas = new JdbcPreparedStatement(this.conn,
"select null as TABLE_SCHEM, null as TABLE_CATALOG") { //$NON-NLS-1$
@Override
ExecutionResult execute(final String queryText,
final int startingRow, final int maxRows,
final int requestSize, final String nextToken)
throws SQLException {
this.data.add("TABLE_SCHEM", "", 0); //$NON-NLS-1$ //$NON-NLS-2$
this.data.add("TABLE_CATALOG", "", 0); //$NON-NLS-1$ //$NON-NLS-2$
return new ExecutionResult(null, 1);
}
};
}
this.getSchemas.clearParameters();
return this.getSchemas.executeQuery();
}
@Override
public ResultSet getSuperTables(final String catalog,
final String schemaPattern, final String tableNamePattern)
throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getSuperTypes(final String catalog,
final String schemaPattern, final String typeNamePattern)
throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getTablePrivileges(final String catalog,
final String schemaPattern, final String tableNamePattern)
throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getTableTypes() throws SQLException {
checkOpen();
if (this.getTableTypes == null) {
this.getTableTypes = new JdbcPreparedStatement(this.conn,
"select 'TABLE' as TABLE_TYPE;") { //$NON-NLS-1$
@Override
ExecutionResult execute(final String queryText,
final int startingRow, final int maxRows,
final int requestSize, final String nextToken)
throws SQLException {
this.data.add("TABLE_TYPE", "TABLE", 0); //$NON-NLS-1$ //$NON-NLS-2$
return new ExecutionResult(null, 1);
}
};
}
this.getTableTypes.clearParameters();
return this.getTableTypes.executeQuery();
}
@Override
public synchronized ResultSet getTables(final String c, final String s,
String t, final String[] types) throws SQLException {
if (this.getTables == null) {
this.getTables = new ListDomainsStatement(this.conn, null);
}
this.getTables.clearParameters();
checkOpen();
t = (t == null || t.length() == 0) ? "%" : t.toUpperCase(); //$NON-NLS-1$
// String sql =
// "select null as TABLE_CAT, null as TABLE_SCHEM, upper(name) as TABLE_NAME,"
// +
// " upper(type) as TABLE_TYPE, null as REMARKS, null as TYPE_CAT, null as TYPE_SCHEM,"
// +
// " null as TYPE_NAME, null as SELF_REFERENCING_COL_NAME, null as REF_GENERATION from domains"
// + " where TABLE_NAME like '" + escape(t) + "'";
//
// if (types != null) {
// sql += " and TABLE_TYPE in (";
// for (int i = 0; i < types.length; i++) {
// if (i > 0) {
// sql += ", ";
// }
// sql += "'" + types[i].toUpperCase() + "'";
// }
// sql += ")";
// }
//
// sql += ";";
return this.getTables
.executeQuery("select * from ALL_TABLES where " + JdbcStatement.DELIMITED_IDENTIFIER_QUOTE //$NON-NLS-1$
+ "TABLE_NAME" + JdbcStatement.DELIMITED_IDENTIFIER_QUOTE + "='" + t + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
@Override
public ResultSet getTypeInfo() throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getUDTs(final String catalog, final String schemaPattern,
final String typeNamePattern, final int[] types)
throws SQLException {
return new JdbcResultSet(null);
}
@Override
public ResultSet getVersionColumns(final String catalog,
final String schema, final String table) throws SQLException {
return new JdbcResultSet(null);
}
@Override
public Connection getConnection() {
return this.conn;
}
@Override
public int getDatabaseMajorVersion() {
return 1;
}
@Override
public int getDatabaseMinorVersion() {
return 0;
}
@Override
public int getDriverMajorVersion() {
return 1;
}
@Override
public int getDriverMinorVersion() {
return 0;
}
@Override
public int getJDBCMajorVersion() {
return 2009;
}
@Override
public int getJDBCMinorVersion() {
return 4;
}
@Override
public int getDefaultTransactionIsolation() {
return Connection.TRANSACTION_SERIALIZABLE;
}
@Override
public int getMaxBinaryLiteralLength() {
return 0;
}
@Override
public int getMaxCatalogNameLength() {
return 0;
}
@Override
public int getMaxCharLiteralLength() {
return 0;
}
@Override
public int getMaxColumnNameLength() {
return 0;
}
@Override
public int getMaxColumnsInGroupBy() {
return 0;
}
@Override
public int getMaxColumnsInIndex() {
return 0;
}
@Override
public int getMaxColumnsInOrderBy() {
return 0;
}
@Override
public int getMaxColumnsInSelect() {
return 0;
}
@Override
public int getMaxColumnsInTable() {
return 0;
}
@Override
public int getMaxConnections() {
return 0;
}
@Override
public int getMaxCursorNameLength() {
return 0;
}
@Override
public int getMaxIndexLength() {
return 0;
}
@Override
public int getMaxProcedureNameLength() {
return 0;
}
@Override
public int getMaxRowSize() {
return 0;
}
@Override
public int getMaxSchemaNameLength() {
return 0;
}
@Override
public int getMaxStatementLength() {
return 0;
}
@Override
public int getMaxStatements() {
return 0;
}
@Override
public int getMaxTableNameLength() {
return 0;
}
@Override
public int getMaxTablesInSelect() {
return 0;
}
@Override
public int getMaxUserNameLength() {
return 0;
}
@Override
public int getResultSetHoldability() {
return ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
@Override
public int getSQLStateType() {
return sqlStateSQL99;
}
@Override
public String getDatabaseProductName() {
return "SimpleDB"; //$NON-NLS-1$
}
@Override
public String getDatabaseProductVersion() throws SQLException {
return "2009.4.15"; // ? //$NON-NLS-1$
}
@Override
public String getDriverName() {
return "SimpleDB"; //$NON-NLS-1$
}
@Override
public String getDriverVersion() {
return "1.0"; //$NON-NLS-1$
}
@Override
public String getExtraNameCharacters() {
return ""; //$NON-NLS-1$
}
@Override
public String getCatalogSeparator() {
return "."; //$NON-NLS-1$
}
@Override
public String getCatalogTerm() {
return "catalog"; //$NON-NLS-1$
}
@Override
public String getSchemaTerm() {
return "schema"; //$NON-NLS-1$
}
@Override
public String getProcedureTerm() {
return "not_implemented"; //$NON-NLS-1$
}
@Override
public String getSearchStringEscape() {
return null;
}
@Override
public String getIdentifierQuoteString() {
return "`"; //$NON-NLS-1$
}
@Override
public String getSQLKeywords() {
return ""; //$NON-NLS-1$
}
@Override
public String getNumericFunctions() {
return ""; //$NON-NLS-1$
}
@Override
public String getStringFunctions() {
return ""; //$NON-NLS-1$
}
@Override
public String getSystemFunctions() {
return ""; //$NON-NLS-1$
}
@Override
public String getTimeDateFunctions() {
return ""; //$NON-NLS-1$
}
@Override
public String getURL() {
return null;
}
@Override
public String getUserName() {
return null;
}
@Override
public boolean allProceduresAreCallable() {
return false;
}
@Override
public boolean allTablesAreSelectable() {
return true;
}
@Override
public boolean dataDefinitionCausesTransactionCommit() {
return false;
}
@Override
public boolean dataDefinitionIgnoredInTransactions() {
return false;
}
@Override
public boolean doesMaxRowSizeIncludeBlobs() {
return false;
}
@Override
public boolean deletesAreDetected(final int type) {
return false;
}
@Override
public boolean insertsAreDetected(final int type) {
return false;
}
@Override
public boolean isCatalogAtStart() {
return true;
}
@Override
public boolean locatorsUpdateCopy() {
return false;
}
@Override
public boolean nullPlusNonNullIsNull() {
return true;
}
@Override
public boolean nullsAreSortedAtEnd() {
return !nullsAreSortedAtStart();
}
@Override
public boolean nullsAreSortedAtStart() {
return true;
}
@Override
public boolean nullsAreSortedHigh() {
return true;
}
@Override
public boolean nullsAreSortedLow() {
return !nullsAreSortedHigh();
}
@Override
public boolean othersDeletesAreVisible(final int type) {
return false;
}
@Override
public boolean othersInsertsAreVisible(final int type) {
return false;
}
@Override
public boolean othersUpdatesAreVisible(final int type) {
return false;
}
@Override
public boolean ownDeletesAreVisible(final int type) {
return false;
}
@Override
public boolean ownInsertsAreVisible(final int type) {
return false;
}
@Override
public boolean ownUpdatesAreVisible(final int type) {
return false;
}
@Override
public boolean storesLowerCaseIdentifiers() {
return false;
}
@Override
public boolean storesLowerCaseQuotedIdentifiers() {
return false;
}
@Override
public boolean storesMixedCaseIdentifiers() {
return true;
}
@Override
public boolean storesMixedCaseQuotedIdentifiers() {
return false;
}
@Override
public boolean storesUpperCaseIdentifiers() {
return false;
}
@Override
public boolean storesUpperCaseQuotedIdentifiers() {
return false;
}
@Override
public boolean supportsAlterTableWithAddColumn() {
return false;
}
@Override
public boolean supportsAlterTableWithDropColumn() {
return false;
}
@Override
public boolean supportsANSI92EntryLevelSQL() {
return false;
}
@Override
public boolean supportsANSI92FullSQL() {
return false;
}
@Override
public boolean supportsANSI92IntermediateSQL() {
return false;
}
@Override
public boolean supportsBatchUpdates() {
return true;
}
@Override
public boolean supportsCatalogsInDataManipulation() {
return false;
}
@Override
public boolean supportsCatalogsInIndexDefinitions() {
return false;
}
@Override
public boolean supportsCatalogsInPrivilegeDefinitions() {
return false;
}
@Override
public boolean supportsCatalogsInProcedureCalls() {
return false;
}
@Override
public boolean supportsCatalogsInTableDefinitions() {
return false;
}
@Override
public boolean supportsColumnAliasing() {
return true;
}
@Override
public boolean supportsConvert() {
return false;
}
@Override
public boolean supportsConvert(final int fromType, final int toType) {
return false;
}
@Override
public boolean supportsCorrelatedSubqueries() {
return false;
}
@Override
public boolean supportsDataDefinitionAndDataManipulationTransactions() {
return true;
}
@Override
public boolean supportsDataManipulationTransactionsOnly() {
return false;
}
@Override
public boolean supportsDifferentTableCorrelationNames() {
return false;
}
@Override
public boolean supportsExpressionsInOrderBy() {
return true;
}
@Override
public boolean supportsMinimumSQLGrammar() {
return true;
}
@Override
public boolean supportsCoreSQLGrammar() {
return true;
}
@Override
public boolean supportsExtendedSQLGrammar() {
return false;
}
@Override
public boolean supportsLimitedOuterJoins() {
return true;
}
@Override
public boolean supportsFullOuterJoins() {
return false;
}
@Override
public boolean supportsGetGeneratedKeys() {
return false;
}
@Override
public boolean supportsGroupBy() {
return true;
}
@Override
public boolean supportsGroupByBeyondSelect() {
return false;
}
@Override
public boolean supportsGroupByUnrelated() {
return false;
}
@Override
public boolean supportsIntegrityEnhancementFacility() {
return false;
}
@Override
public boolean supportsLikeEscapeClause() {
return false;
}
@Override
public boolean supportsMixedCaseIdentifiers() {
return true;
}
@Override
public boolean supportsMixedCaseQuotedIdentifiers() {
return false;
}
@Override
public boolean supportsMultipleOpenResults() {
return false;
}
@Override
public boolean supportsMultipleResultSets() {
return false;
}
@Override
public boolean supportsMultipleTransactions() {
return true;
}
@Override
public boolean supportsNamedParameters() {
return true;
}
@Override
public boolean supportsNonNullableColumns() {
return true;
}
@Override
public boolean supportsOpenCursorsAcrossCommit() {
return false;
}
@Override
public boolean supportsOpenCursorsAcrossRollback() {
return false;
}
@Override
public boolean supportsOpenStatementsAcrossCommit() {
return false;
}
@Override
public boolean supportsOpenStatementsAcrossRollback() {
return false;
}
@Override
public boolean supportsOrderByUnrelated() {
return false;
}
@Override
public boolean supportsOuterJoins() {
return true;
}
@Override
public boolean supportsPositionedDelete() {
return false;
}
@Override
public boolean supportsPositionedUpdate() {
return false;
}
@Override
public boolean supportsResultSetConcurrency(final int t, final int c) {
return t == ResultSet.TYPE_FORWARD_ONLY
&& c == ResultSet.CONCUR_READ_ONLY;
}
@Override
public boolean supportsResultSetHoldability(final int h) {
return h == ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
@Override
public boolean supportsResultSetType(final int t) {
return t == ResultSet.TYPE_FORWARD_ONLY;
}
@Override
public boolean supportsSavepoints() {
return false;
}
@Override
public boolean supportsSchemasInDataManipulation() {
return false;
}
@Override
public boolean supportsSchemasInIndexDefinitions() {
return false;
}
@Override
public boolean supportsSchemasInPrivilegeDefinitions() {
return false;
}
@Override
public boolean supportsSchemasInProcedureCalls() {
return false;
}
@Override
public boolean supportsSchemasInTableDefinitions() {
return false;
}
@Override
public boolean supportsSelectForUpdate() {
return false;
}
@Override
public boolean supportsStatementPooling() {
return false;
}
@Override
public boolean supportsStoredProcedures() {
return false;
}
@Override
public boolean supportsSubqueriesInComparisons() {
return false;
}
@Override
public boolean supportsSubqueriesInExists() {
return false;
}
@Override
public boolean supportsSubqueriesInIns() {
return false;
}
@Override
public boolean supportsSubqueriesInQuantifieds() {
return false;
}
@Override
public boolean supportsTableCorrelationNames() {
return false;
}
@Override
public boolean supportsTransactionIsolationLevel(final int level) {
return level == Connection.TRANSACTION_SERIALIZABLE;
}
@Override
public boolean supportsTransactions() {
return true;
}
@Override
public boolean supportsUnion() {
return true;
}
@Override
public boolean supportsUnionAll() {
return true;
}
@Override
public boolean updatesAreDetected(final int type) {
return false;
}
@Override
public boolean usesLocalFilePerTable() {
return false;
}
@Override
public boolean usesLocalFiles() {
return true;
}
@Override
public boolean isReadOnly() throws SQLException {
return this.conn.isReadOnly();
}
@Override
public boolean autoCommitFailureClosesAllResultSets() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public ResultSet getClientInfoProperties() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ResultSet getFunctionColumns(final String arg0, final String arg1, final String arg2,
final String arg3) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ResultSet getFunctions(final String arg0, final String arg1, final String arg2)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public RowIdLifetime getRowIdLifetime() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ResultSet getSchemas(final String arg0, final String arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isWrapperFor(final Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(final Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ResultSet getPseudoColumns(String catalog, String schemaPattern,
String tableNamePattern, String columnNamePattern)
throws SQLException {
return null;
}
@Override
public boolean generatedKeyAlwaysReturned() throws SQLException {
return false;
}
}
| 8,027 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcPreparedStatement.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.internal.driver;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.JdbcConnection;
/**
* JDBC PersistedStatement implementation for the Amazon SimpleDB. Converts queries into Amazon API calls.
*/
public class JdbcPreparedStatement extends JdbcStatement implements PreparedStatement, ParameterMetaData {
public JdbcPreparedStatement(final JdbcConnection conn, final String sql) {
super(conn);
this.sql = sql;
}
@Override
public void clearParameters() throws SQLException {
if (this.params != null) {
this.params.clear();
}
}
private void setParameter(final int index, final Object value) {
if (this.params == null) {
this.params = new ArrayList<>();
}
for (int i = this.params.size() - 1; i < index - 1; i++) {
this.params.add(null);
}
this.params.set(index - 1, value);
}
@Override
public boolean execute() throws SQLException {
return execute(this.sql);
}
@Override
public ResultSet executeQuery() throws SQLException {
return executeQuery(this.sql);
}
@Override
public int executeUpdate() throws SQLException {
return executeUpdate(this.sql);
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return getResultSet().getMetaData();
}
@Override
public void setBoolean(final int parameterIndex, final boolean x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setByte(final int parameterIndex, final byte x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setBytes(final int parameterIndex, final byte[] x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setDate(final int parameterIndex, final Date x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setDate(final int parameterIndex, final Date x, final Calendar cal) throws SQLException {
// NB! ignores Calendar
setParameter(parameterIndex, x);
}
@Override
public void setDouble(final int parameterIndex, final double x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setFloat(final int parameterIndex, final float x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setInt(final int parameterIndex, final int x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setLong(final int parameterIndex, final long x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setNull(final int parameterIndex, final int sqlType) throws SQLException {
setParameter(parameterIndex, null);
}
@Override
public void setNull(final int parameterIndex, final int sqlType, final String typeName) throws SQLException {
setParameter(parameterIndex, null);
}
@Override
public void setObject(final int parameterIndex, final Object x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setObject(final int parameterIndex, final Object x, final int targetSqlType) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setObject(final int parameterIndex, final Object x, final int targetSqlType, final int scale)
throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setShort(final int parameterIndex, final short x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setString(final int parameterIndex, final String x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setTime(final int parameterIndex, final Time x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setTime(final int parameterIndex, final Time x, final Calendar cal) throws SQLException {
// NB! ignores Calendar
setParameter(parameterIndex, x);
}
@Override
public void setTimestamp(final int parameterIndex, final Timestamp x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setTimestamp(final int parameterIndex, final Timestamp x, final Calendar cal) throws SQLException {
// NB! ignores Calendar
setParameter(parameterIndex, x);
}
@Override
public void setArray(final int parameterIndex, final Array x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setBigDecimal(final int parameterIndex, final BigDecimal x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setBlob(final int parameterIndex, final Blob x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setClob(final int parameterIndex, final Clob x) throws SQLException {
setParameter(parameterIndex, x);
}
@Override
public void setURL(final int parameterIndex, final URL x) throws SQLException {
setParameter(parameterIndex, x);
}
// PARAMETER META DATA //////////////////////////////////////////////////////
@Override
public ParameterMetaData getParameterMetaData() {
return this;
}
@Override
public int getParameterCount() throws SQLException {
checkOpen();
return this.params == null ? 0 : this.params.size();
}
@Override
public String getParameterClassName(final int param) throws SQLException {
checkOpen();
return "java.lang.String"; //$NON-NLS-1$
}
@Override
public String getParameterTypeName(final int pos) {
return "VARCHAR"; //$NON-NLS-1$
}
@Override
public int getParameterType(final int pos) {
return Types.VARCHAR;
}
@Override
public int getParameterMode(final int pos) {
return parameterModeIn;
}
@Override
public int getPrecision(final int pos) {
return 0;
}
@Override
public int getScale(final int pos) {
return 0;
}
@Override
public int isNullable(final int pos) {
return parameterNullable;
}
@Override
public boolean isSigned(final int pos) {
return true;
}
public Statement getStatement() {
return this;
}
// NOT SUPPORTED ////////////////////////////////////////////////////////////
@Override
public void addBatch() throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void setAsciiStream(final int parameterIndex, final InputStream x, final int length) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void setBinaryStream(final int parameterIndex, final InputStream x, final int length) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void setCharacterStream(final int pos, final Reader reader, final int length) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void setRef(final int i, final Ref x) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void setUnicodeStream(final int pos, final InputStream x, final int length) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public void setAsciiStream(final int arg0, final InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setAsciiStream(final int arg0, final InputStream arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBinaryStream(final int arg0, final InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBinaryStream(final int arg0, final InputStream arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBlob(final int arg0, final InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBlob(final int arg0, final InputStream arg1, final long arg2) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setCharacterStream(final int arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setCharacterStream(final int arg0, final Reader arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setClob(final int arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setClob(final int arg0, final Reader arg1, final long arg2) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNCharacterStream(final int arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNCharacterStream(final int arg0, final Reader arg1, final long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNClob(final int arg0, final NClob arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNClob(final int arg0, final Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNClob(final int arg0, final Reader arg1, final long arg2) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNString(final int arg0, final String arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setRowId(final int arg0, final RowId arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setSQLXML(final int arg0, final SQLXML arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isPoolable() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void setPoolable(final boolean arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isWrapperFor(final Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(final Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
| 8,028 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/SimpleDBDriverValuesProvider.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.internal.driver;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.datatools.connectivity.drivers.DefaultDriverValuesProvider;
import org.eclipse.datatools.connectivity.drivers.IDriverValuesProvider;
import org.osgi.framework.Bundle;
/**
* Searches for the driver jars in the driver plugin if present to provide the list to the driver UI.
*/
public class SimpleDBDriverValuesProvider extends DefaultDriverValuesProvider {
public String getDriverDirName() {
return "lib"; //$NON-NLS-1$
}
@SuppressWarnings("unchecked")
@Override
public String createDefaultValue(final String key) {
/**
* Check to see if the wrapper plug-in is in the Eclipse environment. If it is we'll use it and grab the driver jar
* from there.
*/
if (key.equals(IDriverValuesProvider.VALUE_CREATE_DEFAULT)) {
Bundle[] bundles = Platform.getBundles("com.amazonaws.eclipse.datatools.enablement.simpledb.driver", null); //$NON-NLS-1$
if (bundles != null && bundles.length > 0) {
Enumeration<URL> jars = bundles[0].findEntries(getDriverDirName(), "*.jar", true); //$NON-NLS-1$
while (jars != null && jars.hasMoreElements()) {
URL url = jars.nextElement();
if (url != null) {
return Boolean.toString(true);
}
}
}
}
if (key.equals(IDriverValuesProvider.VALUE_JARLIST)) {
Bundle[] bundles = Platform.getBundles("com.amazonaws.eclipse.datatools.enablement.simpledb.driver", null); //$NON-NLS-1$
if (bundles != null && bundles.length > 0) {
Enumeration<URL> jars = bundles[0].findEntries(getDriverDirName(), "*.jar", true); //$NON-NLS-1$
StringBuffer urls = null;
while (jars != null && jars.hasMoreElements()) {
URL url = jars.nextElement();
if (url != null) {
try {
url = FileLocator.toFileURL(url);
IPath path = new Path(url.getFile());
if (urls == null) {
urls = new StringBuffer();
}
if (urls.length() > 0) {
urls.append(";"); //$NON-NLS-1$
}
urls.append(path.toOSString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (urls != null && urls.length() > 0) {
return urls.toString();
}
}
}
return super.createDefaultValue(key);
}
}
| 8,029 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.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.internal.driver;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.datatools.modelbase.sql.query.PredicateBasic;
import org.eclipse.datatools.modelbase.sql.query.QueryDeleteStatement;
import org.eclipse.datatools.modelbase.sql.query.QueryInsertStatement;
import org.eclipse.datatools.modelbase.sql.query.QuerySearchCondition;
import org.eclipse.datatools.modelbase.sql.query.QuerySelectStatement;
import org.eclipse.datatools.modelbase.sql.query.QueryUpdateStatement;
import org.eclipse.datatools.modelbase.sql.query.UpdateAssignmentExpression;
import org.eclipse.datatools.modelbase.sql.query.ValueExpressionColumn;
import org.eclipse.datatools.modelbase.sql.query.util.SQLQuerySourceFormat;
import org.eclipse.datatools.sqltools.parsers.sql.query.SQLQueryParseResult;
import org.eclipse.datatools.sqltools.parsers.sql.query.SQLQueryParserFactory;
import org.eclipse.datatools.sqltools.parsers.sql.query.SQLQueryParserManager;
import org.eclipse.emf.common.util.EList;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.JdbcConnection;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.SimpleDBItemName;
import com.amazonaws.services.simpledb.model.Attribute;
import com.amazonaws.services.simpledb.model.BatchPutAttributesRequest;
import com.amazonaws.services.simpledb.model.CreateDomainRequest;
import com.amazonaws.services.simpledb.model.DeleteAttributesRequest;
import com.amazonaws.services.simpledb.model.DeleteDomainRequest;
import com.amazonaws.services.simpledb.model.Item;
import com.amazonaws.services.simpledb.model.PutAttributesRequest;
import com.amazonaws.services.simpledb.model.ReplaceableAttribute;
import com.amazonaws.services.simpledb.model.SelectRequest;
import com.amazonaws.services.simpledb.model.SelectResult;
/**
* JDBC Statement implementation for the Amazon SimpleDB. Converts queries into Amazon API calls.
*/
public class JdbcStatement implements Statement {
private static final Pattern PATTERN_LIMIT = Pattern.compile("\\s+limit\\s+\\d+"); //$NON-NLS-1$
private static final Pattern PATTERN_SELECT_STAR = Pattern.compile("^\\s*select\\s+\\*\\s+.*"); //$NON-NLS-1$
private static final Pattern PATTERN_SELECT_COUNT = Pattern.compile("^\\s*select\\s+count\\s*\\(\\s*\\*\\s*\\).*"); //$NON-NLS-1$
private static final Pattern PATTERN_WHITESPACE_END = Pattern.compile("\\s+$"); //$NON-NLS-1$
private static final Pattern PATTERN_WHITESPACE_BEGIN = Pattern.compile("^\\s+"); //$NON-NLS-1$
private static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\s+"); //$NON-NLS-1$
private static final Pattern PATTERN_FROM_CLAUSE = Pattern.compile("from\\s+[\\S&&[^,]]+"); //$NON-NLS-1$
/** Amazon SDB prefers all the identifiers in the select clause to be quoted with the given character. */
public static final char DELIMITED_IDENTIFIER_QUOTE = '`';
private static final int MAX_ITEMS_PER_QUERY_RESPONSE = 251;
JdbcConnection conn;
String sql = null;
JdbcResultSet resultSet;
int maxRows = 0; // max. number of rows which can be returned by this statement
RawData data;
/** PreparedStatement parameters or filled from usual statement upon parsing */
List<Object> params = null;
boolean cancel = false;
public JdbcStatement(final JdbcConnection conn) {
this.conn = conn;
this.resultSet = new JdbcResultSet(this);
}
@Override
public void close() throws SQLException {
this.resultSet.close();
this.data = new RawData();
}
protected final void checkOpen() throws SQLException {
if (this.resultSet == null || !this.resultSet.isOpen()) {
throw new SQLException("statement is closed"); //$NON-NLS-1$
}
}
@Override
public boolean execute(final String sql) throws SQLException {
close();
this.sql = sql;
if (this.sql == null) {
throw new SQLException("sql is null");
}
trimSQL();
String lowcaseSql = this.sql.toLowerCase();
if (!lowcaseSql.startsWith("select ")) {
executeUpdate(this.sql);
return false; // no ResultSet
}
if (this.sql.length() == 0) {
throw new SQLException("empty sql");
}
int maxRows = getMaxRows();
// System.out.println("GET MAXROWS: " + maxRows);
int limit = -1;
boolean countQuery = PATTERN_SELECT_COUNT.matcher(lowcaseSql).matches();
if (!countQuery) {
// NB! Assuming here that limit word is never a part of an identifier, e.g. attribute
Matcher m = PATTERN_LIMIT.matcher(lowcaseSql);
if (m.find()) {
int limitPos = m.start();
int endPos = m.end();
Pattern p = Pattern.compile("\\d+"); //$NON-NLS-1$
String limitExpression = lowcaseSql.substring(limitPos, endPos);
m = p.matcher(limitExpression);
if (m.find()) {
limit = Integer.parseInt(limitExpression.substring(m.start(), m.end()).trim());
if (limit >= 0 && (limit < maxRows || maxRows <= 0)) {
maxRows = limit;
}
}
}
if (limit < 0 && maxRows > 0) {
this.sql += " limit " + maxRows;
}
} else {
maxRows = 1;
}
// System.out.println("EFFECTIVE MAXROWS: " + maxRows);
int row = 0;
ExecutionResult result = new ExecutionResult(null, -1);
do {
result = execute(this.sql, row, maxRows, MAX_ITEMS_PER_QUERY_RESPONSE, result.nextToken);
if (result == null) {
break;
}
this.resultSet.open();
row += result.items;
if (maxRows > 0 && row >= maxRows) { // reached the limit
// if (result.nextToken != null) {
// this.resultSet.warning = new SQLWarning("This request has exceeded the limits. The NextToken value is: "
// + result.nextToken);
// }
break;
}
// System.out.println("NEXT TOKEN: " + result.nextToken);
} while (result.nextToken != null && result.nextToken.length() > 0);
return true; //this.data.getRowNum() > 0;
}
private void extractColumnNamesFromSelect() throws SQLException {
String sqlToParse = this.sql;
String lowcaseSql = sqlToParse.toLowerCase();
/*
* If we know that the query doesn't explicitly specify column names
* (ex: "select *" or "select count(...)") then we can optimize and bail
* out rather than trying to parse the query.
*/
if (PATTERN_SELECT_STAR.matcher(lowcaseSql).find() || PATTERN_SELECT_COUNT.matcher(lowcaseSql).find()) {
return;
}
// strip 'limit', generic parser doesn't like it
// NB! Assuming here that limit word is never a part of an identifier, e.g. attribute
Matcher m = PATTERN_LIMIT.matcher(lowcaseSql);
if (m.find()) {
int limitPos = m.start();
int endPos = m.end();
sqlToParse = this.sql.substring(0, limitPos);
if (this.sql.length() - endPos > 0) {
sqlToParse += this.sql.substring(endPos, this.sql.length());
}
}
// Convert double quotes to single quotes since the generic parser chokes on double
// quotes but they're perfectly valid for SimpleDB
sqlToParse = sqlToParse.replace('"', '\'');
try {
SQLQueryParserManager manager = createParserManager();
SQLQueryParseResult res = manager.parseQuery(sqlToParse);
if (res.getSQLStatement() instanceof QuerySelectStatement) {
QuerySelectStatement stmt = (QuerySelectStatement) res.getSQLStatement();
EList<?> columns = stmt.getQueryExpr().getQuery().getColumnList();
if (columns != null) {
String[] columnNames = new String[columns.size()];
for (int i = 0; i < columns.size(); i++) {
Object column = columns.get(i);
if (!(column instanceof ValueExpressionColumn)) {
continue;
}
String name = ((ValueExpressionColumn) column).getName();
if ("*".equals(name)) { // just in case
continue;
}
columnNames[i] = name;
}
// validate names
for (String columnName : columnNames) {
if (columnName == null) {
return; // failed to get all the column names, putting it to data map will break everything
}
}
for (String columnName : columnNames) {
this.data.addAttribute(columnName);
}
}
}
} catch (Exception e) {
// ignore atm - most probably this is a custom query from scrapbook where column order is not important
// throw wrapIntoSqlException(e);
}
}
private SQLQueryParserManager createParserManager() {
SQLQueryParserManager manager = SQLQueryParserManager.getInstance();
SQLQuerySourceFormat format = SQLQuerySourceFormat.copyDefaultFormat();
format.setDelimitedIdentifierQuote(DELIMITED_IDENTIFIER_QUOTE);
format.setPreserveSourceFormat(true);
manager.configParser(format, null /*Arrays.asList(new PostParseProcessor[] { new DataTypeResolver(false) })*/);
manager.setParserFactory(new SQLQueryParserFactory(manager.getSourceFormat()) {
@Override
public ValueExpressionColumn createColumnExpression(final String aColumnName) {
//if (statementTypeOnly) {return null;}
ValueExpressionColumn colExpr = super.createColumnExpression(aColumnName);
colExpr.setName(convertSQLIdentifierToCatalogFormat(aColumnName, getDelimitedIdentifierQuote()));
return colExpr;
}
});
return manager;
}
SQLException wrapIntoSqlException(final Exception e) {
SQLException ex;
if (e instanceof SQLException) {
ex = (SQLException) e;
} else {
ex = new SQLException(e.getLocalizedMessage());
ex.initCause(e);
}
return ex;
}
static String convertSQLIdentifierToCatalogFormat(final String sqlIdentifier, final char idDelimiterQuote) {
String catalogIdentifier = sqlIdentifier;
if (sqlIdentifier != null) {
String delimiter = String.valueOf(idDelimiterQuote);
boolean isDelimited = sqlIdentifier.startsWith(delimiter) && sqlIdentifier.endsWith(delimiter);
boolean containsQuotedDelimiters = sqlIdentifier.indexOf(delimiter + delimiter) > -1;
if (isDelimited) {
catalogIdentifier = sqlIdentifier.substring(1, sqlIdentifier.length() - 1);
if (containsQuotedDelimiters) {
catalogIdentifier = catalogIdentifier.replaceAll(delimiter + delimiter, delimiter);
}
} else {
catalogIdentifier = sqlIdentifier;
}
}
return catalogIdentifier;
}
private void trimSQL() {
this.sql = this.sql.trim();
Matcher m = PATTERN_WHITESPACE_BEGIN.matcher(this.sql);
if (m.find()) {
this.sql = this.sql.substring(m.end());
}
m = PATTERN_WHITESPACE_END.matcher(this.sql);
if (m.find()) {
this.sql = this.sql.substring(0, m.start());
}
if (this.sql.endsWith(";")) {
this.sql = this.sql.substring(0, this.sql.length() - 1);
}
}
public String getDomainName() {
Matcher m = PATTERN_FROM_CLAUSE.matcher(this.sql);
if (m.find()) {
String fromExpression = this.sql.substring(m.start(), m.end());
m = PATTERN_WHITESPACE.matcher(fromExpression);
if (m.find()) {
String domainName = convertSQLIdentifierToCatalogFormat(fromExpression.substring(m.end()),
DELIMITED_IDENTIFIER_QUOTE);
return domainName;
}
}
return null;
}
/*
* Collect as many items as SimpleDB allows and return the NextToken, which
* is used to continue the query in a subsequent call to SimpleDB.
*/
ExecutionResult execute(final String queryText, final int startingRow, final int maxRows, final int requestSize,
final String nextToken) throws SQLException {
if (this.data.getPersistedColumnNum() == 0) {
extractColumnNamesFromSelect();
}
// System.out.println("FINAL QUERY: " + queryText);
SelectRequest request = new SelectRequest();
request.setSelectExpression(queryText);
if (nextToken != null) {
request.setNextToken(nextToken);
}
SelectResult queryResult;
try {
queryResult = this.conn.getClient().select(request);
} catch (Exception e) {
throw wrapIntoSqlException(e);
}
boolean shouldAddItemName = this.data.getPersistedColumnNum() == 0
|| this.data.getAttributes().contains(SimpleDBItemName.ITEM_HEADER);
int row = startingRow;
// List<GetAttributesResponse> responses = new ArrayList<GetAttributesResponse>();
for (Item item : queryResult.getItems()) {
if (this.cancel) {
break;
}
if (shouldAddItemName) {
this.data.addItemName(item.getName(), row);
}
List<Attribute> attributes = item.getAttributes();
for (Attribute attr : attributes) {
this.data.add(attr.getName(), attr.getValue(), row);
}
if (attributes.isEmpty()) {
this.data.ensureRows(row);
}
// GetAttributesRequest aRequest = new GetAttributesRequest();
// aRequest.setItemName(item.getName());
// aRequest.setDomainName(getDomainName() /*request.getDomainName()*/);
// try {
// responses.add(this.conn.service.getAttributes(aRequest));
// } catch (Exception e) {
// throw wrapIntoSqlException(e);
// }
row++;
}
// row = startingRow;
// for (GetAttributesResponse aResponse : responses) {
// if (this.cancel) {
// break;
// }
//
// try {
// GetAttributesResult aResult = aResponse.getGetAttributesResult();
// for (Attribute attribute : aResult.getAttribute()) {
// this.data.add(attribute.getName(), attribute.getValue(), row);
// }
// } catch (Exception e) {
// throw wrapIntoSqlException(e);
// }
//
// row++;
// }
String newNextToken = queryResult.getNextToken();
return new ExecutionResult(newNextToken, row - startingRow);
}
@Override
public ResultSet executeQuery(final String sql) throws SQLException {
if (execute(sql)) {
return getResultSet();
} else {
throw new SQLException("query didn't return a ResultSet");
}
}
@Override
@SuppressWarnings("unchecked")
public int executeUpdate(final String inSql) throws SQLException {
this.sql = inSql;
if (this.sql == null) {
throw new SQLException("sql is null");
}
trimSQL();
if (this.sql.length() == 0) {
throw new SQLException("empty sql");
}
String lowcaseSql = this.sql.toLowerCase();
Object req = null;
// TODO use patterns
if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$
int pos = this.sql.lastIndexOf(" ");
String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(),
DELIMITED_IDENTIFIER_QUOTE);
req = new CreateDomainRequest().withDomainName(domain);
} else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$
|| lowcaseSql.startsWith("drop table")) {
int pos = this.sql.lastIndexOf(" ");
String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(),
DELIMITED_IDENTIFIER_QUOTE);
List<String> pending = this.conn.getPendingColumns(domain);
if (pending != null) {
pending = new ArrayList<>(pending);
for (String attr : pending) {
this.conn.removePendingColumn(domain, attr);
}
}
req = new DeleteDomainRequest().withDomainName(domain);
} else if (lowcaseSql.startsWith("delete from")) {
req = prepareDeleteRowRequest();
} else if (lowcaseSql.startsWith("alter table ")) {
req = prepareDropAttributeRequest();
} else if (lowcaseSql.startsWith("insert ")) {
req = prepareInsertRequest();
} else if (lowcaseSql.startsWith("update ")) {
req = prepareUpdateRequest();
} else if (lowcaseSql.startsWith("create testdomain ")) {
req = new ArrayList<>();
String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$
DELIMITED_IDENTIFIER_QUOTE);
((List<Object>) req).add(new CreateDomainRequest().withDomainName(domain));
ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE);
for (int i = 0; i < 570; i++) {
((List<Object>) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr));
}
}
if (req != null) {
int result = executeSDBRequest(req);
if (this.params != null) {
for (Object obj : this.params) {
if (obj instanceof SimpleDBItemName) {
((SimpleDBItemName) obj).setPersisted(true);
}
}
}
return result;
}
throw new SQLException("unsupported update: " + this.sql);
}
@SuppressWarnings("unchecked")
int executeSDBRequest(final Object req) throws SQLException {
try {
if (req == null) {
// do nothing
return 0;
} else if (req instanceof Collection) {
int sum = 0;
for (Object singleReq : (Collection<Object>) req) {
sum += executeSDBRequest(singleReq);
}
return sum;
} else if (req instanceof CreateDomainRequest) {
this.conn.getClient().createDomain((CreateDomainRequest) req);
return 0;
} else if (req instanceof DeleteDomainRequest) {
this.conn.getClient().deleteDomain((DeleteDomainRequest) req);
return 0;
} else if (req instanceof PutAttributesRequest) {
this.conn.getClient().putAttributes((PutAttributesRequest) req);
return 1;
} else if (req instanceof BatchPutAttributesRequest) {
this.conn.getClient().batchPutAttributes((BatchPutAttributesRequest) req);
return ((BatchPutAttributesRequest) req).getItems().size();
} else if (req instanceof DeleteAttributesRequest) {
this.conn.getClient().deleteAttributes((DeleteAttributesRequest) req);
List<Attribute> attribute = ((DeleteAttributesRequest) req).getAttributes();
return attribute == null || attribute.isEmpty() ? 1 : 0;
} else {
throw new SQLException("unsupported query");
}
} catch (AmazonServiceException e) {
throw wrapIntoSqlException(e);
}
}
List<Object> prepareUpdateRequest() throws SQLException {
if (this.sql.toLowerCase().indexOf(" set ") < 0) { // workaround for DTP bug - sends update statements without set of any columns
return new ArrayList<>();
}
try {
SQLQueryParserManager manager = createParserManager();
SQLQueryParseResult res = manager.parseQuery(this.sql);
QueryUpdateStatement qs = (QueryUpdateStatement) res.getQueryStatement();
QuerySearchCondition whereClause = qs.getWhereClause();
if (!(whereClause instanceof PredicateBasic)) {
throw new SQLException("current SDB JDBC version supports only simple expression `" //$NON-NLS-1$
+ SimpleDBItemName.ITEM_HEADER + "`='<something>' in WHERE clause");
}
if (this.params == null) {
// TODO some time later extract the parameters from the parsed simple statement
}
if (this.params == null) {
throw new SQLException("current SDB JDBC version supports only parameterized queries");
}
String domain = qs.getTargetTable().getName();
String item = unwrapItemValue(this.params.get(this.params.size() - 1));
EList<?> assignmentClause = qs.getAssignmentClause();
if (this.params != null && this.params.size() - 1 != assignmentClause.size()) { // last param is an Item name, thus -1
throw new SQLException("number of set params doesn't match");
}
int tally = 0;
List<ReplaceableAttribute> attrs = new ArrayList<>();
for (Object assign : assignmentClause) {
UpdateAssignmentExpression assignExp = (UpdateAssignmentExpression) assign;
EList<?> cols = assignExp.getTargetColumnList();
ValueExpressionColumn col = (ValueExpressionColumn) cols.get(0);
String colName = col.getName();
String colValue = (String) this.params.get(tally);
if (colValue != null) {
ReplaceableAttribute attr = new ReplaceableAttribute().withName(colName).withValue(colValue).withReplace(Boolean.TRUE);
attrs.add(attr);
}
++tally;
}
tally = 0;
List<Attribute> deleteAttrs = new ArrayList<>();
for (Object assign : assignmentClause) {
UpdateAssignmentExpression assignExp = (UpdateAssignmentExpression) assign;
EList<?> cols = assignExp.getTargetColumnList();
ValueExpressionColumn col = (ValueExpressionColumn) cols.get(0);
String colName = col.getName();
if (SimpleDBItemName.ITEM_HEADER.equals(colName)) { // TODO how we could use ColumnType here instead of hardcoded ColumnName?
throw new SQLException("item name cannot be edited once created");
}
String colValue = (String) this.params.get(tally);
if (colValue == null) {
Attribute attr = new Attribute().withName(colName).withValue(colValue);
deleteAttrs.add(attr);
}
++tally;
}
List<Object> reqs = new ArrayList<>();
if (!attrs.isEmpty()) {
PutAttributesRequest req = new PutAttributesRequest().withDomainName(domain).withItemName(item);
req.setAttributes(attrs);
reqs.add(req);
}
if (!deleteAttrs.isEmpty()) {
DeleteAttributesRequest dreq = new DeleteAttributesRequest().withDomainName(domain).withItemName(item);
dreq.setAttributes(deleteAttrs);
reqs.add(dreq);
}
return reqs;
} catch (Exception e) {
throw wrapIntoSqlException(e);
}
}
PutAttributesRequest prepareInsertRequest() throws SQLException {
try {
SQLQueryParserManager manager = createParserManager();
SQLQueryParseResult res = manager.parseQuery(this.sql);
QueryInsertStatement qs = (QueryInsertStatement) res.getQueryStatement();
String domain = qs.getTargetTable().getName();
if (this.params == null) {
// TODO some time later extract the parameters from the parsed simple statement
}
if (this.params == null) {
throw new SQLException("current SDB JDBC version supports only parameterized queries");
}
EList<?> targetColumns = qs.getTargetColumnList();
// ValuesRow values = (ValuesRow)qs.getSourceValuesRowList().get(0);
if (this.params != null && this.params.size() != targetColumns.size()) {
throw new SQLException("number of set params doesn't match");
}
int tally = 0;
String item = null;
List<ReplaceableAttribute> attrs = new ArrayList<>();
for (Object assign : targetColumns) {
ValueExpressionColumn col = (ValueExpressionColumn) assign;
String colName = col.getName();
if (tally == 0 && !SimpleDBItemName.ITEM_HEADER.equals(colName)) {
throw new SQLException("first parameter must be " + DELIMITED_IDENTIFIER_QUOTE + SimpleDBItemName.ITEM_HEADER //$NON-NLS-1$
+ DELIMITED_IDENTIFIER_QUOTE);
}
Object colValue = this.params.get(tally);
if (colValue != null) {
if (SimpleDBItemName.ITEM_HEADER.equals(colName)) { // TODO how we could use ColumnType here instead of hardcoded ColumnName?
item = unwrapItemValue(colValue);
} else {
if (colValue instanceof String[]) {
for (String val : (String[]) colValue) {
ReplaceableAttribute attr = new ReplaceableAttribute().withName(colName).withValue(val).withReplace(Boolean.TRUE);
attrs.add(attr);
}
} else {
ReplaceableAttribute attr = new ReplaceableAttribute().withName(colName).withValue((String) colValue).withReplace(Boolean.TRUE);
attrs.add(attr);
}
}
}
++tally;
}
PutAttributesRequest req = new PutAttributesRequest().withDomainName(domain).withItemName(item);
req.setAttributes(attrs);
return req;
} catch (Exception e) {
throw wrapIntoSqlException(e);
}
}
Object prepareDeleteRowRequest() throws SQLException {
try {
SQLQueryParserManager manager = createParserManager();
SQLQueryParseResult res = manager.parseQuery(this.sql);
QueryDeleteStatement qs = (QueryDeleteStatement) res.getQueryStatement();
String domain = qs.getTargetTable().getName();
if (this.params == null) {
// TODO some time later extract the parameters from the parsed simple statement
}
if (this.params == null) {
throw new SQLException("current SDB JDBC version supports only parameterized queries");
}
Object firstParam = this.params.get(0);
String item = unwrapItemValue(firstParam);
DeleteAttributesRequest req = new DeleteAttributesRequest().withDomainName(domain).withItemName(item);
return req;
} catch (Exception e) {
throw wrapIntoSqlException(e);
}
}
Object prepareDropAttributeRequest() throws SQLException {
try {
// SQLQueryParserManager manager = SQLQueryParserManager.getInstance();
// SQLQuerySourceFormat format = SQLQuerySourceFormat.copyDefaultFormat();
// format.setDelimitedIdentifierQuote('`');
// manager.configParser(format, null);
//
// SQLQueryParseResult res = manager.parseQuery(this.sql);
// QueryDeleteStatement qs = (QueryDeleteStatement) res.getQueryStatement();
//
// String domain = qs.getTargetTable().getName();
// TODO use patterns
if (!this.sql.startsWith("alter table") || this.sql.indexOf(" drop ") < 0) { //$NON-NLS-1$
throw new SQLException("unsupported alter table statement");
}
int pos = this.sql.indexOf(" ", "alter table ".length() + 1); //$NON-NLS-1$ //$NON-NLS-2$
String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring("alter table ".length(), pos).trim(), //$NON-NLS-1$
DELIMITED_IDENTIFIER_QUOTE);
pos = this.sql.indexOf("drop "); //$NON-NLS-1$
String attrName = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + "drop ".length()).trim(),
DELIMITED_IDENTIFIER_QUOTE);
this.conn.removePendingColumn(domain, attrName);
Attribute attr = new Attribute().withName(attrName).withValue(null);
List<Attribute> attrs = new ArrayList<>();
attrs.add(attr);
this.sql = "select itemName from " + DELIMITED_IDENTIFIER_QUOTE + domain + DELIMITED_IDENTIFIER_QUOTE //$NON-NLS-1$
+ " where " + DELIMITED_IDENTIFIER_QUOTE + attrName + DELIMITED_IDENTIFIER_QUOTE + " is not null";
ResultSet rs = executeQuery(this.sql);
List<DeleteAttributesRequest> reqs = new ArrayList<>();
while (rs.next()) {
String item = rs.getString(1);
DeleteAttributesRequest dar = new DeleteAttributesRequest().withDomainName(domain).withItemName(item);
dar.setAttributes(attrs);
reqs.add(dar);
}
return reqs;
} catch (Exception e) {
throw wrapIntoSqlException(e);
}
}
@SuppressWarnings("unchecked")
private String unwrapItemValue(final Object param) {
String item;
if (param instanceof SimpleDBItemName) {
item = ((SimpleDBItemName) param).getItemName();
} else if (param instanceof Collection) {
item = ((Collection<String>) param).iterator().next();
} else if (param instanceof String[]) {
item = ((String[]) param)[0];
} else {
item = (String) param;
}
return item;
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public ResultSet getResultSet() throws SQLException {
return this.resultSet;
}
@Override
public int getUpdateCount() throws SQLException {
return -1; // we return ResultSet
}
@Override
public void setCursorName(final String name) throws SQLException {
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public Connection getConnection() throws SQLException {
return this.conn;
}
@Override
public void cancel() throws SQLException {
// this.resultSet.checkOpen();
this.cancel = true;
}
@Override
public int getMaxRows() throws SQLException {
return this.maxRows;
}
@Override
public void setMaxRows(final int maxRows) throws SQLException {
// System.out.println("SETTING MAXROWS: " + maxRows);
if (maxRows < 0) {
throw new SQLException("max row count must be >= 0"); //$NON-NLS-1$
}
this.maxRows = maxRows;
}
@Override
public int getMaxFieldSize() throws SQLException {
return 0;
}
@Override
public void setMaxFieldSize(final int max) throws SQLException {
if (max < 0) {
throw new SQLException("max field size " + max + " cannot be negative"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
@Override
public int getFetchSize() throws SQLException {
return this.resultSet.getFetchSize();
}
@Override
public void setFetchSize(final int r) throws SQLException {
this.resultSet.setFetchSize(r);
}
@Override
public int getFetchDirection() throws SQLException {
return this.resultSet.getFetchDirection();
}
@Override
public void setFetchDirection(final int d) throws SQLException {
this.resultSet.setFetchDirection(d);
}
@Override
public boolean getMoreResults() throws SQLException {
return getMoreResults(0);
}
@Override
public boolean getMoreResults(final int c) throws SQLException {
// checkOpen();
close();
return false;
}
@Override
public int getResultSetConcurrency() throws SQLException {
return getResultSet().getConcurrency();
}
@Override
public int getResultSetHoldability() throws SQLException {
return ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
@Override
public int getResultSetType() throws SQLException {
return getResultSet().getType();
}
@Override
public void setEscapeProcessing(final boolean enable) {
}
// NOT SUPPORTED ////////////////////////////////////////////////////////////
@Override
public int getQueryTimeout() throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
// return this.timeout;
}
@Override
public void setQueryTimeout(final int seconds) throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
// if (seconds < 0) {
// throw new SQLException("query timeout must be >= 0");
// }
// this.timeout = seconds;
}
@Override
public void addBatch(final String sql) throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
}
@Override
public void clearBatch() throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
}
@Override
public int[] executeBatch() throws SQLException {
throw new SQLException("unsupported by SDB yet"); //$NON-NLS-1$
}
@Override
public boolean execute(final String sql, final int[] colinds) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public boolean execute(final String sql, final String[] colnames) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public int executeUpdate(final String sql, final int autoKeys) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public int executeUpdate(final String sql, final int[] colinds) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public int executeUpdate(final String sql, final String[] cols) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
@Override
public boolean execute(final String sql, final int autokeys) throws SQLException {
throw new SQLException("unsupported by SDB"); //$NON-NLS-1$
}
// INNER CLASSES ////////////////////////////////////////////////////////////
/**
* Collects item information in the format given by SimpleDB and aggregates it into a tabular format.
*/
class RawData {
// A list of rows, where each row is a map of columnIndex to values
private List<Map<Integer, List<String>>> rows;
// A list of column names (attributes)
private List<String> columns;
private List<Integer> itemNameColumn;
/**
* Constructor
*/
public RawData() {
this.rows = new ArrayList<>();
this.columns = new ArrayList<>();
this.itemNameColumn = new ArrayList<>();
}
/**
* Returns the attribute values at the given row and column.
*
* @param row
* Corresponds to the n'th item in the result
* @param column
* Corresponds to the n'th overall attribute. The attribute may or may not apply to this item.
* @return A list of values or null if the attribute doesn't apply to this item.
*/
public List<String> get(final int row, final int column) {
if (this.rows.size() > row) {
return this.rows.get(row).get(column);
} else {
return null;
}
}
/**
* A convenience method to return a delimited string of the attribute value at the specified row and column.
*
* @param row
* @param column
* @param delimiter
* @return found value; multi-value separated by given delimiter
* @see #get(int,int)
*/
public String getString(final int row, final int column, final String delimiter) {
return join(get(row, column), delimiter);
}
/**
* Add the given value as an item name value at the given row. A new column is added to the table if there was no
* such yet.
*
* @param value
* @param rowNum
*/
public void addItemName(final String value, final int rowNum) {
ensureItemNameColumn(rowNum);
int column = add(SimpleDBItemName.ITEM_HEADER, value, rowNum);
this.itemNameColumn.set(rowNum, column);
}
public boolean isItemNameColumn(final int row, final int column) {
if (row < 0 || row >= this.rows.size()) {
List<String> attrs = getAttributes();
return !attrs.isEmpty() && SimpleDBItemName.ITEM_HEADER.equals(attrs.get(column));
}
ensureItemNameColumn(row);
Integer itemName = this.itemNameColumn.get(row);
return itemName != null && itemName.intValue() == column;
}
public int getItemNameColumn(final int row) {
if (row < 0 || row >= this.rows.size()) {
List<String> attrs = getAttributes();
return attrs.indexOf(SimpleDBItemName.ITEM_HEADER);
}
ensureItemNameColumn(row);
Integer itemName = this.itemNameColumn.get(row);
return itemName != null ? itemName.intValue() : -1;
}
private void ensureItemNameColumn(final int row) {
for (int i = this.itemNameColumn.size() - 1; i < row; i++) {
this.itemNameColumn.add(null);
}
}
public int addAttribute(final String attribute) {
int column = this.columns.indexOf(attribute);
if (column < 0) {
column = this.columns.size();
this.columns.add(attribute);
}
return column;
}
/**
* Add the given attribute/value pair at the given row. The attribute may already exist, in which case the value is
* added to the list of existing attributes. Otherwise, a new column is added to the table.
*
* @param attribute
* @param value
* @param rowNum
* @return index of the attribute
*/
public int add(final String attribute, final String value, final int rowNum) {
int column = this.columns.indexOf(attribute);
if (column < 0) {
column = this.columns.size();
this.columns.add(attribute);
JdbcStatement.this.conn.removePendingColumn(getDomainName(), attribute); // real data from SDB came, safe to remove the pending column
}
ensureRows(rowNum);
Map<Integer, List<String>> row = this.rows.get(rowNum);
List<String> values = row.get(column);
if (values == null) {
values = new ArrayList<>();
row.put(column, values);
}
values.add(value);
return column;
}
public void ensureRows(final int rowNum) {
for (int i = this.rows.size() - 1; i < rowNum; i++) {
this.rows.add(new HashMap<Integer, List<String>>());
}
}
/**
* @return The number of rows/items in the query
*/
public int getRowNum() {
return this.rows.size();
}
/**
* @return The number of columns/attributes in the query
*/
public int getColumnNum() {
int size = this.columns.size();
List<String> pendings = JdbcStatement.this.conn.getPendingColumns(JdbcStatement.this.getDomainName());
if (pendings != null && !pendings.isEmpty() && this.columns.isEmpty()) {
++size; // +1 for ItemName - special case when there is just freshly added attributes and there is no content in the domain
}
if (pendings != null) {
pendings = new ArrayList<>(pendings);
pendings.removeAll(this.columns);
size += pendings.size();
}
return size;
}
/**
* @return The number of columns/attributes existing in the SDB, i.e. no pending columns
*/
public int getPersistedColumnNum() {
return this.columns.size();
}
/**
* @return A list of attributes in the order as they exist in the table
*/
public List<String> getAttributes() {
ArrayList<String> attrs = new ArrayList<>(this.columns);
List<String> pendings = JdbcStatement.this.conn.getPendingColumns(JdbcStatement.this.getDomainName());
if (pendings != null && !pendings.isEmpty() && this.columns.isEmpty()) {
attrs.add(SimpleDBItemName.ITEM_HEADER); // special case when there is just freshly added attributes and there is no content in the domain
}
if (pendings != null) {
pendings = new ArrayList<>(pendings);
pendings.removeAll(this.columns);
attrs.addAll(pendings);
}
return attrs;
}
/*
* Private interface
*/
/*
* Join the items in a Collection of Strings with the given delimiter
*/
private String join(final Collection<String> s, final String delimiter) {
if (s == null) {
return ""; //$NON-NLS-1$
}
StringBuilder builder = new StringBuilder();
Iterator<String> iter = s.iterator();
while (iter.hasNext()) {
builder.append(iter.next());
if (iter.hasNext()) {
builder.append(delimiter);
}
}
return builder.toString();
}
// TODO reimplement one day to use map
/* @return index (starts from 0) of the attribute with the given name */
public int findAttribute(final String name) throws SQLException {
int c = -1;
for (int i = 0; i < this.columns.size(); i++) {
String cur = this.columns.get(i);
if (name.equalsIgnoreCase(cur)
|| (cur.toUpperCase().endsWith(name.toUpperCase()) && cur.charAt(cur.length() - name.length()) == '.')) {
if (c == -1) {
c = i;
} else {
throw new SQLException("ambiguous column: '" + name + "'"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
if (c == -1) {
List<String> pendings = JdbcStatement.this.conn.getPendingColumns(JdbcStatement.this.getDomainName());
if (pendings != null) {
pendings = new ArrayList<>(pendings);
pendings.removeAll(this.columns);
for (int i = 0; i < pendings.size(); i++) {
String cur = pendings.get(i);
if (name.equalsIgnoreCase(cur)
|| (cur.toUpperCase().endsWith(name.toUpperCase()) && cur.charAt(cur.length() - name.length()) == '.')) {
if (c == -1) {
c = i + Math.max(this.columns.size(), 1); // 1 - special case when there is just freshly added attributes and there is no content in the domain
} else {
throw new SQLException("ambiguous column: '" + name + "'"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
}
if (c == -1) {
throw new SQLException("no such column: '" + name + "'"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
return c;
}
}
}
/*
* Bundle the NextToken and number of items fetched in the last query.
*/
static class ExecutionResult {
public ExecutionResult(final String nextToken, final int items) {
this.nextToken = nextToken;
this.items = items;
}
public final String nextToken;
public final int items;
}
@Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isPoolable() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void setPoolable(final boolean poolable) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isWrapperFor(final Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(final Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void closeOnCompletion() throws SQLException {
}
@Override
public boolean isCloseOnCompletion() throws SQLException {
return false;
}
}
| 8,030 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor/SimpleDBIDDataAccessor.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.enablement.simpledb.editor;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.eclipse.datatools.sqltools.data.internal.core.common.DefaultColumnDataAccessor;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.SimpleDBItemName;
public class SimpleDBIDDataAccessor extends DefaultColumnDataAccessor {
@Override
public boolean supportsInlineEdit() {
return false;
}
@Override
public Object read(final ResultSet rs, final int col, final int type, final boolean snippet) throws SQLException,
IOException {
return rs.getObject(col + 1);
}
@Override
public Object deserialize(final String val, final int type) {
return new SimpleDBItemName(val);
}
@Override
public String[] writeValuesExprArgs(final PreparedStatement pst, final int start, final Object val, final int type)
throws SQLException, IOException {
pst.setObject(start + 1, val);
return new String[] { argString(getLabel(val, type), type) };
}
}
| 8,031 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor/SDBTextEditor.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.enablement.simpledb.editor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.datatools.sqltools.data.internal.core.editor.RowDataImpl;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.IExternalTableDataEditor;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.ITableDataEditor;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataCell;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataEditor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.SimpleDBItemName;
import com.amazonaws.eclipse.datatools.enablement.simpledb.editor.wizard.SDBTableDataWizard;
import com.amazonaws.eclipse.datatools.enablement.simpledb.editor.wizard.SDBTableIdDataWizard;
public class SDBTextEditor implements IExternalTableDataEditor {
public SDBTextEditor() {}
@Override
public void externalEdit(final ITableDataEditor editor) {
Object obj = editor;
if (obj instanceof TableDataEditor) {
externalEdit((TableDataEditor)obj);
}
}
/* (non-Javadoc)
* @see org.eclipse.datatools.sqltools.data.internal.ui.editor.IExternalTableDataEditor#externalEdit(org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataEditor)
*/
public void externalEdit(final TableDataEditor editor) {
if (editor.getCursor().getColumn() == 0) {
Object value = getCellValue(editor);
if ((value instanceof SimpleDBItemName && !((SimpleDBItemName) value).isPersisted()) || value instanceof String
|| value == null) {
SDBTableIdDataWizard wizard = new SDBTableIdDataWizard(editor);
WizardDialog dialog = new WizardDialog(editor.getSite().getShell(), wizard);
dialog.setPageSize(400, 250);
dialog.open();
} else {
ErrorDialog ed = new ErrorDialog(editor.getEditorSite().getShell(), Messages.idErrorDialogTitle,
Messages.idErrorDialogMessage,
new Status(IStatus.INFO, Activator.PLUGIN_ID, Messages.idErrorStatusMessage), SWT.ERROR);
ed.open();
}
} else {
SDBTableDataWizard wizard = new SDBTableDataWizard(editor);
WizardDialog dialog = new WizardDialog(editor.getSite().getShell(), wizard);
dialog.setPageSize(400, 250);
dialog.open();
}
}
private Object getCellValue(final TableDataEditor editor) {
int col = editor.getCursor().getColumn();
StructuredSelection selection = (StructuredSelection) editor.getSelectionProvider().getSelection();
TableDataCell firstElement = (TableDataCell) selection.getFirstElement();
Object row = firstElement.getRow();
if (row instanceof RowDataImpl) {
RowDataImpl rowData = (RowDataImpl) row;
Object value = rowData.getValue(col);
return value;
} else {
//This usually means that the row was just created and no RowDataImpl have been created yet.
return ""; //$NON-NLS-1$
}
}
}
| 8,032 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor/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.enablement.simpledb.editor;
import org.eclipse.osgi.util.NLS;
public class Messages {
private static final String BUNDLE_NAME = "com.amazonaws.eclipse.datatools.enablement.simpledb.editor.messages"; //$NON-NLS-1$
public static String windowTitle;
public static String pageTitle;
public static String idWindowTitle;
public static String idPageTitle;
public static String dialogTitle;
public static String dialogDescription;
public static String labelEditAttributeValues;
public static String newValue;
public static String remove;
public static String add;
public static String edit;
public static String valueToLong;
public static String mainMessage;
public static String idMainMessage;
public static String idErrorDialogMessage;
public static String idErrorDialogTitle;
public static String idErrorStatusMessage;
public static String incorrectDataType;
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
private Messages() {
}
}
| 8,033 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor/SimpleDBDataAccessor.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.enablement.simpledb.editor;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.datatools.sqltools.data.internal.core.common.DefaultColumnDataAccessor;
import org.eclipse.datatools.sqltools.data.internal.core.common.data.PreparedStatementWriter;
import org.eclipse.datatools.sqltools.result.ui.ResultsViewUIPlugin;
import org.eclipse.jface.preference.IPreferenceStore;
public class SimpleDBDataAccessor extends DefaultColumnDataAccessor {
/**
* If val is String[] or Collection returns true, otherwise returns super.isSnippet(...) This is to disable in cell
* editing for multiple attribute columns.
*
* @see org.eclipse.datatools.sqltools.data.internal.core.common.DefaultColumnDataAccessor#isSnippet(java.lang.Object,
* int)
*/
@SuppressWarnings("unchecked")
@Override
public boolean isSnippet(final Object val, final int type) {
if (val == null) {
return false;
}
if (val instanceof Collection) {
return true;
}
if (val instanceof String[]) {
return true;
}
return super.isSnippet(val, type);
}
/**
* Converts val to readable string if val is instance of String[] otherwise returns super.getLabel(...)
*
* @see org.eclipse.datatools.sqltools.data.internal.core.common.DefaultColumnDataAccessor#getLabel(java.lang.Object,
* int)
*/
@SuppressWarnings("unchecked")
@Override
public String getLabel(final Object val, final int type) {
if (val == null) {
IPreferenceStore store = ResultsViewUIPlugin.getDefault().getPreferenceStore();
return store.getString("org.eclipse.datatools.sqltools.result.preferences.display.nulldisplaystr"); // org.eclipse.datatools.sqltools.result.internal.ui.PreferenceConstants.SQL_RESULTS_VIEW_NULL_STRING //$NON-NLS-1$
}
if (val instanceof String[]) {
return Arrays.toString((String[]) val);
}
if (val instanceof LinkedList && ((List) val).size() == 1) { // ID - single name
List<String> values = (List<String>) val;
return values.get(0);
}
if (val instanceof ArrayList) { // multi-value column - draw in [] brackets
return val.toString();
}
return super.getLabel(val, type);
}
@SuppressWarnings("unchecked")
@Override
public String[] writeSetAssArgs(final PreparedStatement pst, final int start, Object val, final int type)
throws SQLException, IOException {
if (val instanceof List) {
List<String> values = (List<String>) val;
val = values.toArray(new String[values.size()]);
}
if (val instanceof String[]) {
String[] values = (String[]) val;
String[] result = new String[values.length];
int tally = 0;
for (String singleVal : values) {
PreparedStatementWriter.write(pst, start + tally, type, singleVal);
result[tally++] = argString(getLabel(singleVal, type), type);
}
return result;
} else {
return super.writeSetAssArgs(pst, start, val, type);
}
}
@SuppressWarnings("unchecked")
@Override
public String[] writeWhereCondArgs(final PreparedStatement pst, final int start, final Object val, final int type)
throws SQLException, IOException {
if (val != null) {
Object v = null;
if (val instanceof List && ((List<?>) val).size() == 1) {
List<?> values = (List<?>) val;
v = values.get(0);
} else if (val instanceof String[] && ((String[]) val).length == 1) {
String[] values = (String[]) val;
v = values[0];
} else {
v = val;
}
PreparedStatementWriter.write(pst, start, type, v);
return new String[] { argString(getLabel(v, type), type) };
} else {
return new String[] {};
}
}
@SuppressWarnings("unchecked")
@Override
public String getSetAss(Object val) {
if (val instanceof List) {
List<String> values = (List<String>) val;
val = values.toArray(new String[values.size()]);
}
if (val instanceof String[]) {
String[] values = (String[]) val;
String quotedColumnName = getQuotedColumnName();
StringBuffer buf = new StringBuffer((quotedColumnName.length() + 1) * values.length);
for (int i = 0; i < values.length; i++) {
if (i > 0) {
buf.append(","); //$NON-NLS-1$
}
buf.append(quotedColumnName).append("=?"); //$NON-NLS-1$
}
return buf.toString();
} else {
return super.getSetAss(val);
}
}
}
| 8,034 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor/wizard/SDBTableIdDataWizard.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.enablement.simpledb.editor.wizard;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataEditor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.eclipse.datatools.enablement.simpledb.editor.Messages;
public class SDBTableIdDataWizard extends Wizard {
private final TableDataEditor editor;
private SDBTableIdDataWizardPage page;
public SDBTableIdDataWizard(final TableDataEditor editor) {
this.editor = editor;
setNeedsProgressMonitor(false);
setWindowTitle(Messages.idWindowTitle);
}
@Override
public void addPages() {
this.page = new SDBTableIdDataWizardPage(this.editor);
ImageDescriptor image = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID,
"icons/sdb-wizard-75x66-shadow.png"); //$NON-NLS-1$
this.page.setImageDescriptor(image);
addPage(this.page);
}
@Override
public boolean performFinish() {
this.page.saveData();
return true;
}
@Override
public boolean canFinish() {
return this.page.isPageComplete();
}
}
| 8,035 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor/wizard/SDBTableDataWizardPage.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.enablement.simpledb.editor.wizard;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.datatools.sqltools.data.internal.core.editor.RowDataImpl;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataCell;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataEditor;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.eclipse.datatools.enablement.simpledb.editor.Messages;
public class SDBTableDataWizardPage extends WizardPage {
private static final int INDENT = 6;
private final TableDataEditor editor;
private int col;
private RowDataImpl rowData;
private Table table;
private Button edit;
private Button add;
private Button remove;
private TableColumn tColumn;
public SDBTableDataWizardPage(final TableDataEditor editor) {
super(Messages.pageTitle);
setTitle(Messages.pageTitle);
setMessage(Messages.mainMessage);
this.editor = editor;
}
@Override
public void createControl(final Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
FormLayout layout = new FormLayout();
layout.marginWidth = INDENT;
layout.marginHeight = INDENT;
composite.setLayout(layout);
final Label l = new Label(composite, SWT.None);
l.setText(Messages.labelEditAttributeValues);
this.table = new Table(composite, SWT.FULL_SELECTION | SWT.HIDE_SELECTION | SWT.BORDER | SWT.V_SCROLL
| SWT.H_SCROLL | SWT.MULTI);
this.add = new Button(composite, SWT.None);
this.remove = new Button(composite, SWT.None);
this.edit = new Button(composite, SWT.None);
this.table.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(final SelectionEvent se) {
SDBTableDataWizardPage.this.edit.setEnabled(SDBTableDataWizardPage.this.table.getSelection().length == 1);
SDBTableDataWizardPage.this.remove.setEnabled(SDBTableDataWizardPage.this.table.getSelection().length > 0);
}
@Override
public void widgetDefaultSelected(final SelectionEvent arg0) {
}
});
this.table.addMouseListener(new MouseListener() {
@Override
public void mouseUp(final MouseEvent arg0) {
}
@Override
public void mouseDown(final MouseEvent arg0) {
}
@Override
public void mouseDoubleClick(final MouseEvent arg0) {
if (SDBTableDataWizardPage.this.table.getSelectionCount() > 0) {
String newValue = getNewValue(SDBTableDataWizardPage.this.table.getSelection()[0].getText());
if (newValue != null) {
SDBTableDataWizardPage.this.table.getSelection()[0].setText(newValue);
SDBTableDataWizardPage.this.tColumn.pack();
}
}
}
});
this.tColumn = new TableColumn(this.table, SWT.NONE);
createContent();
this.tColumn.pack();
this.edit.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(final SelectionEvent arg0) {
String newValue = getNewValue(SDBTableDataWizardPage.this.table.getSelection()[0].getText());
if (newValue != null) {
SDBTableDataWizardPage.this.table.getSelection()[0].setText(newValue);
SDBTableDataWizardPage.this.tColumn.pack();
}
}
@Override
public void widgetDefaultSelected(final SelectionEvent arg0) {
}
});
this.add.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(final SelectionEvent arg0) {
String newValue = getNewValue(Messages.newValue);
if (newValue != null) {
TableItem item = createItem(newValue);
SDBTableDataWizardPage.this.table.setSelection(item);
SDBTableDataWizardPage.this.remove.setEnabled(true);
SDBTableDataWizardPage.this.edit.setEnabled(true);
SDBTableDataWizardPage.this.tColumn.pack();
}
}
@Override
public void widgetDefaultSelected(final SelectionEvent arg0) {
}
});
this.remove.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(final SelectionEvent arg0) {
int[] selectionIndices = SDBTableDataWizardPage.this.table.getSelectionIndices();
SDBTableDataWizardPage.this.table.remove(selectionIndices);
if (selectionIndices != null && SDBTableDataWizardPage.this.table.getItemCount() > 0) {
int minSelected = Integer.MAX_VALUE;
for (int i = 0; i < selectionIndices.length; i++) {
if (selectionIndices[i] < minSelected) {
minSelected = selectionIndices[i];
}
}
--minSelected;
if (minSelected < 0 || minSelected == Integer.MAX_VALUE) {
minSelected = 0;
}
try {
SDBTableDataWizardPage.this.table.setSelection(minSelected);
} catch (Exception e) { // just to be on the safe side
e.printStackTrace();
}
}
SDBTableDataWizardPage.this.edit.setEnabled(SDBTableDataWizardPage.this.table.getSelection().length == 1);
SDBTableDataWizardPage.this.remove.setEnabled(SDBTableDataWizardPage.this.table.getSelection().length > 0);
SDBTableDataWizardPage.this.tColumn.pack();
}
@Override
public void widgetDefaultSelected(final SelectionEvent arg0) {
}
});
FormData d = new FormData();
d.top = new FormAttachment(0, 0);
d.left = new FormAttachment(0, 0);
d.right = new FormAttachment(100, 0);
l.setLayoutData(d);
d = new FormData();
d.top = new FormAttachment(l, INDENT);
d.left = new FormAttachment(0, 0);
d.right = new FormAttachment(this.remove, -INDENT);
d.bottom = new FormAttachment(100, 0);
this.table.setLayoutData(d);
this.add.setText(Messages.add);
d = new FormData();
d.right = new FormAttachment(100, 0);
d.top = new FormAttachment(l, INDENT);
d.width = 70;
this.add.setLayoutData(d);
this.remove.setText(Messages.remove);
d = new FormData();
d.top = new FormAttachment(this.add, 0);
d.right = new FormAttachment(100, 0);
d.width = 70;
this.remove.setLayoutData(d);
this.edit.setText(Messages.edit);
d = new FormData();
d.right = new FormAttachment(100, 0);
d.top = new FormAttachment(this.remove, INDENT);
d.width = 70;
this.edit.setLayoutData(d);
setControl(composite);
}
private String getNewValue(final String value) {
InputDialog id = new InputDialog(this.editor.getEditorSite().getShell(), Messages.dialogTitle,
Messages.dialogDescription, value, new IInputValidator() {
@Override
public String isValid(final String s) {
if (s.getBytes().length > 1024) {
return Messages.valueToLong;
}
return null;
}
});
if (id.open() == Window.OK) {
return id.getValue();
} else {
return null;
}
}
protected void saveData() {
TableItem[] items = this.table.getItems();
if (this.rowData != null) {
if (items.length == 0) {
this.rowData.updateValue(this.col, null);
} else if (items.length == 1) {
this.rowData.updateValue(this.col, items[0].getText());
} else {
String[] s = createValue(items);
this.rowData.updateValue(this.col, s);
}
try {
Class<?> c = Class.forName(TableDataEditor.class.getCanonicalName());
Field f1 = c.getDeclaredField("tableViewer");//$NON-NLS-1$
f1.setAccessible(true);
TableViewer tv = (TableViewer) f1.get(this.editor);
tv.refresh(this.rowData);
this.editor.getCursor().redraw();
Method m = c.getDeclaredMethod("setDirty", new Class[] { java.lang.Boolean.TYPE });//$NON-NLS-1$
m.setAccessible(true);
m.invoke(this.editor, new Object[] { Boolean.TRUE });
this.editor.setDirtyBackground(this.col, this.editor.getCursor().getRow());
} catch (SecurityException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (ClassNotFoundException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (NoSuchFieldException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (IllegalArgumentException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (IllegalAccessException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (NoSuchMethodException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (InvocationTargetException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
}
}
}
private String[] createValue(final TableItem[] items) {
String[] s = new String[items.length];
for (int i = 0; i < items.length; i++) {
TableItem it = items[i];
s[i] = it.getText();
}
return s;
}
@SuppressWarnings("unchecked")
private void createContent() {
this.col = this.editor.getCursor().getColumn();
StructuredSelection selection = (StructuredSelection) this.editor.getSelectionProvider().getSelection();
TableDataCell firstElement = (TableDataCell) selection.getFirstElement();
Object value = null;
if (firstElement.getRow() instanceof RowDataImpl) {
this.rowData = (RowDataImpl) firstElement.getRow();
value = this.rowData.getValue(this.col);
} else {
//There is no rowData yet, we need to create it ourselves
// ITableData tableData = this.editor.getTableData();
this.rowData = (RowDataImpl) this.editor.getOrCreateRow();
value = firstElement.getRow();
}
if (value instanceof String) {
createItem((String) value);
} else if (value instanceof String[]) {
String[] strings = (String[]) value;
for (String s : strings) {
createItem(s);
}
} else if (value instanceof ArrayList) {
List<String> strings = (List<String>) value;
for (String s : strings) {
createItem(s);
}
}
if (this.table.getItems().length > 0) {
this.table.setSelection(0);
this.remove.setEnabled(true);
this.edit.setEnabled(true);
} else {
this.remove.setEnabled(false);
this.edit.setEnabled(false);
}
}
private TableItem createItem(final String value) {
TableItem item = new TableItem(this.table, SWT.NONE);
item.setText(new String[] { value });
return item;
}
}
| 8,036 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor/wizard/SDBTableIdDataWizardPage.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.enablement.simpledb.editor.wizard;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.datatools.sqltools.data.internal.core.editor.RowDataImpl;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataCell;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataEditor;
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.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.datatools.enablement.simpledb.driver.SimpleDBItemName;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.eclipse.datatools.enablement.simpledb.editor.Messages;
public class SDBTableIdDataWizardPage extends WizardPage {
private static final int INDENT = 6;
private final TableDataEditor editor;
private int col;
private RowDataImpl rowData;
private Text t;
public SDBTableIdDataWizardPage(final TableDataEditor editor) {
super(Messages.idPageTitle);
setTitle(Messages.idPageTitle);
setMessage(Messages.idMainMessage);
this.editor = editor;
}
@Override
public void createControl(final Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
FormLayout layout = new FormLayout();
layout.marginWidth = INDENT;
layout.marginHeight = INDENT;
composite.setLayout(layout);
final Label l = new Label(composite, SWT.None);
l.setText(Messages.labelEditAttributeValues);
this.t = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
this.t.addModifyListener(new ModifyListener() {
@Override
public void modifyText(final ModifyEvent a) {
if (SDBTableIdDataWizardPage.this.t.getText().getBytes().length > 1024) {
setErrorMessage(Messages.valueToLong);
setPageComplete(false);
} else {
setErrorMessage(null);
setPageComplete(true);
}
}
});
FormData d = new FormData();
d.top = new FormAttachment(0, 0);
d.left = new FormAttachment(0, 0);
d.right = new FormAttachment(100, 0);
l.setLayoutData(d);
d = new FormData();
d.top = new FormAttachment(l, INDENT);
d.left = new FormAttachment(0, 0);
d.right = new FormAttachment(100, 0);
d.bottom = new FormAttachment(100, 0);
this.t.setLayoutData(d);
createContent();
setControl(composite);
}
protected void saveData() {
Object oldVal = this.rowData.getValue(this.col);
if (oldVal instanceof SimpleDBItemName) {
((SimpleDBItemName) oldVal).setItemName(this.t.getText());
} else {
this.rowData.updateValue(this.col, this.t.getText());
}
try {
Class<?> c = Class.forName(TableDataEditor.class.getCanonicalName());
Field f1 = c.getDeclaredField("tableViewer");//$NON-NLS-1$
f1.setAccessible(true);
TableViewer tv = (TableViewer) f1.get(this.editor);
tv.refresh(this.rowData);
this.editor.getCursor().redraw();
Method m = c.getDeclaredMethod("setDirty", new Class[] { java.lang.Boolean.TYPE });//$NON-NLS-1$
m.setAccessible(true);
m.invoke(this.editor, new Object[] { Boolean.TRUE });
this.editor.setDirtyBackground(this.col, this.editor.getCursor().getRow());
} catch (SecurityException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (ClassNotFoundException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (NoSuchFieldException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (IllegalArgumentException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (IllegalAccessException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (NoSuchMethodException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
} catch (InvocationTargetException e) {
Activator.logMessage(e.getMessage(), e, IStatus.ERROR);
}
}
private void createContent() {
Object value;
this.col = this.editor.getCursor().getColumn();
StructuredSelection selection = (StructuredSelection) this.editor.getSelectionProvider().getSelection();
TableDataCell firstElement = (TableDataCell) selection.getFirstElement();
Object row = firstElement.getRow();
if (row instanceof RowDataImpl) {
this.rowData = (RowDataImpl) row;
value = this.rowData.getValue(this.col);
} else {
//This usually means that the row was just created and no RowDataImpl have been created yet.
this.rowData = (RowDataImpl) this.editor.getOrCreateRow();
value = ""; //$NON-NLS-1$
}
if (value == null) {
this.t.setText(""); //$NON-NLS-1$
setPageComplete(true);
} else if (value instanceof String) {
this.t.setText((String) value);
setPageComplete(true);
} else if (value instanceof SimpleDBItemName) {
this.t.setText(((SimpleDBItemName) value).getItemName());
setPageComplete(true);
} else {
setErrorMessage((MessageFormat.format(Messages.incorrectDataType, value.getClass().getCanonicalName())));
this.t.setEnabled(false);
setPageComplete(false);
}
}
}
| 8,037 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/editor/wizard/SDBTableDataWizard.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.enablement.simpledb.editor.wizard;
import org.eclipse.datatools.sqltools.data.internal.ui.editor.TableDataEditor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import com.amazonaws.eclipse.datatools.enablement.simpledb.Activator;
import com.amazonaws.eclipse.datatools.enablement.simpledb.editor.Messages;
public class SDBTableDataWizard extends Wizard {
private final TableDataEditor editor;
private SDBTableDataWizardPage page;
public SDBTableDataWizard(final TableDataEditor editor) {
this.editor = editor;
setNeedsProgressMonitor(false);
setWindowTitle(Messages.windowTitle);
}
@Override
public void addPages() {
this.page = new SDBTableDataWizardPage(this.editor);
ImageDescriptor image = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID,
"icons/sdb-wizard-75x66-shadow.png"); //$NON-NLS-1$
this.page.setImageDescriptor(image);
addPage(this.page);
}
@Override
public boolean performFinish() {
this.page.saveData();
return true;
}
@Override
public boolean canFinish() {
return this.page.isPageComplete();
}
}
| 8,038 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/tst/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/tst/com/amazonaws/eclipse/cloudformation/templates/TemplateNodeParserTests.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TemplateNodeParserTests {
@Test
public void testTemplateNodeParser() throws JsonParseException, JsonMappingException, IOException {
TemplateNodeParser parser = new TemplateNodeParser();
Map<String, TemplateNodeParserTestCase> testCases = new ObjectMapper().readValue(
TemplateNodeParserTests.class.getResourceAsStream("template-node-parser-test-cases.json"),
new TypeReference<Map<String, TemplateNodeParserTestCase>>() {});
for (Entry<String, TemplateNodeParserTestCase> entry : testCases.entrySet()) {
System.out.println("Testing test case " + entry.getKey());
testParse(parser, entry.getValue());
}
}
private void testParse(TemplateNodeParser parser, TemplateNodeParserTestCase testCase) {
try {
parser.parse(testCase.intput);
} catch (Exception e) {
if (!testCase.throwException) {
Assert.fail("Assert failure: unexpected exception was thrown: " + e.getMessage());
}
} finally {
Assert.assertEquals(testCase.path, parser.getPath());
}
}
private static class TemplateNodeParserTestCase {
String intput;
Boolean throwException;
String path;
@JsonCreator
public TemplateNodeParserTestCase(
@JsonProperty("input") String intput,
@JsonProperty("throwException") Boolean throwException,
@JsonProperty("path") String path) {
this.intput = intput;
this.throwException = throwException;
this.path = path;
}
}
}
| 8,039 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/tst/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/tst/com/amazonaws/eclipse/cloudformation/templates/schema/v2/TemplateSchemaTests.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
/**
* Test CloudFormation Template schema file to be valid, and up to date.
*/
public class TemplateSchemaTests {
private TemplateSchema schema;
@Before
public void setup() throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
schema = TemplateSchemaParser.getDefaultSchema();
}
@Test
public void testIntrinsicFunctions() {
Map<String, IntrinsicFunction> intrinsicFunctions = schema.getIntrinsicFunctions();
Assert.assertNotNull(intrinsicFunctions);
IntrinsicFunction function = intrinsicFunctions.get("Fn::ImportValue");
Assert.assertTrue(function != null);
Assert.assertEquals("String", function.getReturnType());
}
@Test
public void testPseudoParameters() {
Map<String, PseudoParameter> pseudoParameters = schema.getPseudoParameters();
Assert.assertNotNull(pseudoParameters);
PseudoParameter parameter = pseudoParameters.get("AWS::NotificationARNs");
Assert.assertTrue(parameter != null);
Assert.assertEquals("String", parameter.getArrayType());
}
//TODO more tests for verifying the structure of the schema
}
| 8,040 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/tst/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/tst/com/amazonaws/eclipse/cloudformation/templates/editor/TemplateAutoEditStrategyTests.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.editor;
import static com.amazonaws.eclipse.cloudformation.templates.editor.TemplateAutoEditStrategy.parseOneLine;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Test;
import com.amazonaws.eclipse.cloudformation.templates.editor.TemplateAutoEditStrategy.IndentContext;
import com.amazonaws.eclipse.cloudformation.templates.editor.TemplateAutoEditStrategy.IndentType;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TemplateAutoEditStrategyTests {
@Test
public void testAutoEditStrategy() throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
Map<String, AutoEditStrategyTestCase> testCases = mapper.readValue(
TemplateAutoEditStrategyTests.class.getResourceAsStream("template-auto-edit-test-cases.json"),
new TypeReference<Map<String, AutoEditStrategyTestCase>>() {});
for (Entry<String, AutoEditStrategyTestCase> entry : testCases.entrySet()) {
System.out.println("Testing test case: " + entry.getKey());
AutoEditStrategyTestCase testCase = entry.getValue();
IndentContext expectedIndentContext = new IndentContext(IndentType.valueOf(testCase.indentType), testCase.indentValue);
testParseOneLine(testCase.line, testCase.offset, expectedIndentContext);
}
}
private void testParseOneLine(String line, int offset, IndentContext expectedIndentContext) {
IndentContext actualContext = parseOneLine(line, offset);
assertIndentContextEquals(actualContext, expectedIndentContext);
}
private void assertIndentContextEquals(IndentContext actualContext, IndentContext expectedContext) {
assertTrue(actualContext.indentType == expectedContext.indentType);
assertTrue(actualContext.indentValue == expectedContext.indentValue);
}
private static class AutoEditStrategyTestCase {
String line;
int offset;
String indentType;
int indentValue;
@JsonCreator
public AutoEditStrategyTestCase(
@JsonProperty("line") String line,
@JsonProperty("offset") int offset,
@JsonProperty("indentType") String indentType,
@JsonProperty("indentValue") int indentValue) {
this.line = line;
this.offset = offset;
this.indentType = indentType;
this.indentValue = indentValue;
}
}
}
| 8,041 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/OpenStackEditorAction.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
public class OpenStackEditorAction extends Action {
private final String stackId;
private Region region;
private final boolean autoRefresh;
public OpenStackEditorAction(String stackId) {
this(stackId, null, false);
}
public OpenStackEditorAction(String stackId, Region region, boolean autoRefresh) {
this.setText("Open in Stack Editor");
this.stackId = stackId;
this.region = region;
this.autoRefresh = autoRefresh;
}
@Override
public void run() {
Region selectedRegion = region == null ? RegionUtils.getCurrentRegion() : region;
String endpoint = selectedRegion.getServiceEndpoints().get(ServiceAbbreviations.CLOUD_FORMATION);
String accountId = AwsToolkitCore.getDefault().getCurrentAccountId();
final IEditorInput input = new StackEditorInput(stackId, endpoint, accountId, autoRefresh);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
activeWindow.getActivePage().openEditor(input, "com.amazonaws.eclipse.explorer.cloudformation.stackEditor");
} catch (PartInitException e) {
String errorMessage = "Unable to open the Amazon CloudFormation stack editor: " + e.getMessage();
Status status = new Status(Status.ERROR, CloudFormationPlugin.PLUGIN_ID, errorMessage, e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
});
}
}
| 8,042 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/CloudFormationContentProvider.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import java.util.List;
import com.amazonaws.eclipse.cloudformation.CloudFormationUtils;
import com.amazonaws.eclipse.cloudformation.CloudFormationUtils.StackSummaryConverter;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.explorer.AWSResourcesRootElement;
import com.amazonaws.eclipse.explorer.AbstractContentProvider;
import com.amazonaws.eclipse.explorer.ExplorerNode;
import com.amazonaws.eclipse.explorer.Loading;
import com.amazonaws.services.cloudformation.model.StackSummary;
public class CloudFormationContentProvider extends AbstractContentProvider {
public static final class CloudFormationRootElement {
public static final CloudFormationRootElement ROOT_ELEMENT = new CloudFormationRootElement();
}
public static class StackNode extends ExplorerNode {
private final StackSummary stack;
public StackNode(StackSummary stack) {
super(stack.getStackName(), 0,
loadImage(AwsToolkitCore.IMAGE_STACK), new OpenStackEditorAction(stack.getStackName()));
this.stack = stack;
}
}
@Override
public boolean hasChildren(Object element) {
return (element instanceof AWSResourcesRootElement ||
element instanceof CloudFormationRootElement);
}
@Override
public Object[] loadChildren(Object parentElement) {
if (parentElement instanceof AWSResourcesRootElement) {
return new Object[] {CloudFormationRootElement.ROOT_ELEMENT};
}
if (parentElement instanceof CloudFormationRootElement) {
new DataLoaderThread(parentElement) {
@Override
public Object[] loadData() {
List<StackNode> stackNodes = CloudFormationUtils.listExistingStacks(
new StackSummaryConverter<StackNode>() {
@Override
public StackNode convert(StackSummary stack) {
return new StackNode(stack);
}
});
return stackNodes.toArray();
}
}.start();
}
return Loading.LOADING;
}
@Override
public String getServiceAbbreviation() {
return ServiceAbbreviations.CLOUD_FORMATION;
}
}
| 8,043 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/StackOutputsTable.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import java.util.List;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreePathContentProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.services.cloudformation.model.Output;
class StackOutputsTable extends Composite {
private TreeViewer viewer;
public StackOutputsTable(Composite parent, FormToolkit toolkit) {
super(parent, SWT.NONE);
this.setLayout(new GridLayout());
Composite composite = toolkit.createComposite(this);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TreeColumnLayout tableColumnLayout = new TreeColumnLayout();
composite.setLayout(tableColumnLayout);
StackOutputsContentProvider contentProvider = new StackOutputsContentProvider();
StackOutputsLabelProvider labelProvider = new StackOutputsLabelProvider();
viewer = new TreeViewer(composite, SWT.BORDER | SWT.MULTI);
viewer.getTree().setLinesVisible(true);
viewer.getTree().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTree());
}
private void createColumns(TreeColumnLayout columnLayout, Tree tree) {
createColumn(tree, columnLayout, "Key");
createColumn(tree, columnLayout, "Value");
createColumn(tree, columnLayout, "Description");
}
private TreeColumn createColumn(Tree tree, TreeColumnLayout columnLayout, String text) {
TreeColumn column = new TreeColumn(tree, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
public void updateStackOutputs(List<Output> outputs) {
viewer.setInput(outputs.toArray(new Output[outputs.size()]));
}
private class StackOutputsContentProvider implements ITreePathContentProvider {
private Output[] outputs;
@Override
public void dispose() {}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof Output[]) {
outputs = (Output[]) newInput;
} else {
outputs = new Output[0];
}
}
@Override
public Object[] getElements(Object inputElement) {
return outputs;
}
@Override
public Object[] getChildren(TreePath parentPath) {
return null;
}
@Override
public boolean hasChildren(TreePath path) {
return false;
}
@Override
public TreePath[] getParents(Object element) {
return new TreePath[0];
}
}
private class StackOutputsLabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public void removeListener(ILabelProviderListener listener) {}
@Override
public void dispose() {}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof Output == false) return "";
Output output = (Output) element;
switch (columnIndex) {
case 0: return output.getOutputKey();
case 1: return output.getOutputValue();
case 2: return output.getDescription();
default: return "";
}
}
}
public void setStackOutputs(List<Output> outputs) {
if (outputs == null) viewer.setInput(new Output[0]);
viewer.setInput(outputs.toArray(new Output[outputs.size()]));
}
} | 8,044 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/StackEditorInput.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import org.eclipse.jface.resource.ImageDescriptor;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput;
public class StackEditorInput extends AbstractAwsResourceEditorInput {
private final String stackName;
private final boolean autoRefresh;
public StackEditorInput(String stackName, String endpoint, String accountId) {
this(stackName, endpoint, accountId, false);
}
public StackEditorInput(String stackName, String endpoint, String accountId, boolean autoRefresh) {
super(endpoint, accountId);
this.stackName = stackName;
this.autoRefresh = autoRefresh;
}
public String getStackName() {
return stackName;
}
@Override
public String getName() {
return stackName;
}
public boolean isAutoRefresh() {
return autoRefresh;
}
@Override
public String getToolTipText() {
return "Amazon CloudFormation Stack Editor - " + getName();
}
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_STACK);
}
} | 8,045 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/CloudFormationExplorerActionProvider.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.eclipse.core.resources.ResourcesPlugin;
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.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.navigator.CommonActionProvider;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.DeleteResourceConfirmationDialog;
import com.amazonaws.eclipse.explorer.ContentProviderRegistry;
import com.amazonaws.eclipse.explorer.cloudformation.CloudFormationContentProvider.StackNode;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizard;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizardDataModel.Mode;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.AmazonCloudFormationException;
import com.amazonaws.services.cloudformation.model.CancelUpdateStackRequest;
import com.amazonaws.services.cloudformation.model.DeleteStackRequest;
import com.amazonaws.services.cloudformation.model.GetTemplateRequest;
import com.amazonaws.services.cloudformation.model.GetTemplateResult;
/**
* Action provider when right-clicking on Cloud Formation nodes in the explorer.
*/
public class CloudFormationExplorerActionProvider extends CommonActionProvider {
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.actions.ActionGroup#fillContextMenu(org.eclipse.jface.
* action.IMenuManager)
*/
@Override
public void fillContextMenu(IMenuManager menu) {
StructuredSelection selection = (StructuredSelection) getActionSite().getStructuredViewer().getSelection();
if ( selection.size() != 1 )
return;
menu.add(new CreateStackAction());
Object firstElement = selection.getFirstElement();
if ( firstElement instanceof StackNode ) {
menu.add(new Separator());
menu.add(new SaveStackTemplateAction((StackNode) firstElement));
menu.add(new CancelStackUpdateAction((StackNode) firstElement));
menu.add(new UpdateStackAction((StackNode) firstElement));
menu.add(new DeleteStackAction((StackNode) firstElement));
}
}
private final class CreateStackAction extends Action {
@Override
public String getDescription() {
return "Create a new stack";
}
@Override
public ImageDescriptor getImageDescriptor() {
return CloudFormationPlugin.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD);
}
@Override
public String getText() {
return "Create Stack";
}
@Override
public void run() {
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new CreateStackWizard());
dialog.open();
}
}
private final class UpdateStackAction extends Action {
private final StackNode stack;
public UpdateStackAction(StackNode stack) {
this.stack = stack;
}
@Override
public String getDescription() {
return "Update Stack";
}
@Override
public String getText() {
return "Update Stack";
}
@Override
public void run() {
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new CreateStackWizard(stack.getName(), Mode.Update));
dialog.open();
}
}
private final class CancelStackUpdateAction extends Action {
private final StackNode stack;
public CancelStackUpdateAction(StackNode stack) {
this.stack = stack;
}
@Override
public String getDescription() {
return "Cancel stack update";
}
@Override
public ImageDescriptor getImageDescriptor() {
return CloudFormationPlugin.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public String getText() {
return "Cancel Stack Update";
}
@Override
public void run() {
new Job("Cancel stack update") {
@Override
protected IStatus run(final IProgressMonitor monitor) {
try {
AmazonCloudFormation cloudFormationClient = AwsToolkitCore.getClientFactory()
.getCloudFormationClient();
cloudFormationClient.cancelUpdateStack(new CancelUpdateStackRequest().withStackName(stack.getName()));
} catch ( Exception e ) {
CloudFormationPlugin.getDefault().logError("Couldn't cancel the stack update", e);
return new Status(Status.ERROR, CloudFormationPlugin.PLUGIN_ID,
"Couldn't cancel the stack update:", e);
}
return Status.OK_STATUS;
}
}.schedule();
}
}
private final class SaveStackTemplateAction extends Action {
private final StackNode stack;
public SaveStackTemplateAction(StackNode stack) {
this.stack = stack;
}
@Override
public String getDescription() {
return "Save Stack Template As...";
}
@Override
public ImageDescriptor getImageDescriptor() {
return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_ETOOL_SAVEAS_EDIT);
}
@Override
public String getText() {
return "Save Stack Template As...";
}
@Override
public void run() {
FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
dialog.setFilterPath(ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getAbsolutePath());
final String path = dialog.open();
if ( path != null ) {
new Job("Downloading stack template") {
@Override
protected IStatus run(final IProgressMonitor monitor) {
try {
AmazonCloudFormation cloudFormationClient = AwsToolkitCore.getClientFactory()
.getCloudFormationClient();
GetTemplateResult template = cloudFormationClient.getTemplate(new GetTemplateRequest()
.withStackName(stack.getName()));
String formattedText = template.getTemplateBody();
try {
formattedText = JsonFormatter.format(template.getTemplateBody());
} catch (Exception e) {
CloudFormationPlugin.getDefault().logError("Unable to format template", e);
}
FileUtils.writeStringToFile(new File(path), formattedText);
String workspaceAbsolutePath = ResourcesPlugin.getWorkspace().getRoot()
.getLocation().toFile().getAbsolutePath();
if ( path.startsWith(workspaceAbsolutePath) ) {
final String relPath = path.substring(workspaceAbsolutePath.length());
ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(relPath))
.refreshLocal(1, monitor);
}
} catch ( Exception e ) {
CloudFormationPlugin.getDefault().logError("Couldn't save cloud formation template", e);
return new Status(Status.ERROR, CloudFormationPlugin.PLUGIN_ID,
"Couldn't save cloud formation template:", e);
}
return Status.OK_STATUS;
}
}.schedule();
}
}
}
private final class DeleteStackAction extends Action {
private final StackNode stack;
public DeleteStackAction(StackNode stack) {
this.stack = stack;
this.setText("Delete Stack");
this.setDescription("Deleting a stack deletes all stack resources.");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE));
}
@Override
public void run() {
Dialog dialog = new DeleteResourceConfirmationDialog(Display.getDefault().getActiveShell(),
stack.getName(), "stack");
if (dialog.open() != Window.OK) {
return;
}
Job deleteStackJob = new Job("Deleting Stack...") {
@Override
protected IStatus run(IProgressMonitor monitor) {
AmazonCloudFormation cloudFormation = AwsToolkitCore.getClientFactory().getCloudFormationClient();
IStatus status = Status.OK_STATUS;
try {
cloudFormation.deleteStack(new DeleteStackRequest()
.withStackName(stack.getName()));
} catch (AmazonCloudFormationException e) {
status = new Status(IStatus.ERROR, CloudFormationPlugin.getDefault().getPluginId(), e.getMessage(), e);
}
ContentProviderRegistry.refreshAllContentProviders();
return status;
}
};
deleteStackJob.schedule();
}
}
}
| 8,046 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/JsonFormatter.java | /*
* Copyright 2013 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonFormatter {
public static String format(String text) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
JsonNode tree = mapper.readTree(text);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tree);
}
} | 8,047 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/StackEventsTable.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreePathContentProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.DescribeStackEventsRequest;
import com.amazonaws.services.cloudformation.model.DescribeStackEventsResult;
import com.amazonaws.services.cloudformation.model.StackEvent;
public class StackEventsTable extends Composite {
private TreeViewer viewer;
private final StackEditorInput stackEditorInput;
private final class StackEventsContentProvider implements ITreePathContentProvider {
private StackEvent[] events;
@Override
public void dispose() {}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof StackEvent[]) {
events = (StackEvent[])newInput;
} else {
events = new StackEvent[0];
}
}
@Override
public Object[] getElements(Object inputElement) {
return events;
}
@Override
public Object[] getChildren(TreePath parentPath) {
return null;
}
@Override
public boolean hasChildren(TreePath path) {
return false;
}
@Override
public TreePath[] getParents(Object element) {
return new TreePath[0];
}
}
private final class StackEventsLabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public void removeListener(ILabelProviderListener listener) {}
@Override
public void dispose() {}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof StackEvent == false) return "";
StackEvent stackEvent = (StackEvent)element;
switch (columnIndex) {
case 0: return stackEvent.getTimestamp().toString();
case 1: return stackEvent.getResourceStatus();
case 2: return stackEvent.getResourceType();
case 3: return stackEvent.getLogicalResourceId();
case 4: return stackEvent.getPhysicalResourceId();
case 5: return stackEvent.getResourceStatusReason();
}
return element.toString();
}
}
public StackEventsTable(Composite parent, FormToolkit toolkit, StackEditorInput stackEditorInput) {
super(parent, SWT.NONE);
this.stackEditorInput = stackEditorInput;
this.setLayout(new GridLayout());
Composite composite = toolkit.createComposite(this);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TreeColumnLayout tableColumnLayout = new TreeColumnLayout();
composite.setLayout(tableColumnLayout);
StackEventsContentProvider contentProvider = new StackEventsContentProvider();
StackEventsLabelProvider labelProvider = new StackEventsLabelProvider();
viewer = new TreeViewer(composite, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.getTree().setLinesVisible(true);
viewer.getTree().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTree());
refresh();
}
public void refresh() {
new LoadStackEventsThread().start();
}
private void createColumns(TreeColumnLayout columnLayout, Tree tree) {
createColumn(tree, columnLayout, "Event Time");
createColumn(tree, columnLayout, "State");
createColumn(tree, columnLayout, "Resource Type");
createColumn(tree, columnLayout, "Logical ID");
createColumn(tree, columnLayout, "Physical ID");
createColumn(tree, columnLayout, "Reason");
}
private TreeColumn createColumn(Tree tree, TreeColumnLayout columnLayout, String text) {
TreeColumn column = new TreeColumn(tree, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
private AmazonCloudFormation getClient() {
AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(stackEditorInput.getAccountId());
return clientFactory.getCloudFormationClientByEndpoint(stackEditorInput.getRegionEndpoint());
}
private class LoadStackEventsThread extends Thread {
@Override
public void run() {
try {
DescribeStackEventsRequest request = new DescribeStackEventsRequest().withStackName(stackEditorInput.getStackName());
final List<StackEvent> stackEvents = new LinkedList<>();
DescribeStackEventsResult result = null;
do {
if (result != null) request.setNextToken(result.getNextToken());
result = getClient().describeStackEvents(request);
stackEvents.addAll(result.getStackEvents());
} while (result.getNextToken() != null);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(stackEvents.toArray(new StackEvent[stackEvents.size()]));
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, CloudFormationPlugin.PLUGIN_ID, "Unable to describe events for stack " + stackEditorInput.getStackName(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
} | 8,048 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/StackParametersTable.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import java.util.List;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreePathContentProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.services.cloudformation.model.Parameter;
class StackParametersTable extends Composite {
private TreeViewer viewer;
public StackParametersTable(Composite parent, FormToolkit toolkit) {
super(parent, SWT.NONE);
this.setLayout(new GridLayout());
Composite composite = toolkit.createComposite(this);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TreeColumnLayout tableColumnLayout = new TreeColumnLayout();
composite.setLayout(tableColumnLayout);
StackParametersContentProvider contentProvider = new StackParametersContentProvider();
StackParametersLabelProvider labelProvider = new StackParametersLabelProvider();
viewer = new TreeViewer(composite, SWT.BORDER | SWT.MULTI);
viewer.getTree().setLinesVisible(true);
viewer.getTree().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTree());
}
private void createColumns(TreeColumnLayout columnLayout, Tree tree) {
createColumn(tree, columnLayout, "Key");
createColumn(tree, columnLayout, "Value");
}
private TreeColumn createColumn(Tree tree, TreeColumnLayout columnLayout, String text) {
TreeColumn column = new TreeColumn(tree, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
public void updateStackParameters(List<Parameter> parameters) {
viewer.setInput(parameters.toArray(new Parameter[parameters.size()]));
}
private class StackParametersContentProvider implements ITreePathContentProvider {
Parameter[] parameters;
@Override
public void dispose() {}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof Parameter[]) parameters = (Parameter[])newInput;
else parameters = new Parameter[0];
}
@Override
public Object[] getElements(Object inputElement) {
return parameters;
}
@Override
public Object[] getChildren(TreePath parentPath) {
return null;
}
@Override
public boolean hasChildren(TreePath path) {
return false;
}
@Override
public TreePath[] getParents(Object element) {
return new TreePath[0];
}
}
private class StackParametersLabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public void removeListener(ILabelProviderListener listener) {}
@Override
public void dispose() {}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof Parameter == false) return "";
Parameter parameter = (Parameter)element;
switch (columnIndex) {
case 0: return parameter.getParameterKey();
case 1: return parameter.getParameterValue();
default: return "";
}
}
}
public void setStackParameters(List<Parameter> parameters) {
if (parameters == null) viewer.setInput(new Parameter[0]);
viewer.setInput(parameters.toArray(new Parameter[parameters.size()]));
}
} | 8,049 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/StackEditor.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.DescribeStackResourcesRequest;
import com.amazonaws.services.cloudformation.model.DescribeStacksRequest;
import com.amazonaws.services.cloudformation.model.Stack;
import com.amazonaws.services.cloudformation.model.StackResource;
public class StackEditor extends EditorPart {
private static final String SERVERLESS_REST_API = "ServerlessRestApi";
private static final String SERVERLESS_REST_API_PROD_STAGE = "ServerlessRestApiProdStage";
private static final String[] STABLE_STATES = {
"CREATE_COMPLETE", "CREATE_FAILED", "DELETE_COMPLETE", "DELETE_FAILED", "ROLLBACK_COMPLETE", "ROLLBACK_FAILED",
"UPDATE_COMPLETE", "UPDATE_ROLLBACK_COMPLETE", "UPDATE_ROLLBACK_FAILED"};
private static final List<String> STABLE_STATE_LIST = Arrays.asList(STABLE_STATES);
private StackEditorInput stackEditorInput;
private Text stackNameLabel;
private Text createdLabel;
private Text statusLabel;
private Text createTimeoutLabel;
private Text statusReasonLabel;
private Text lastUpdatedLabel;
private Text descriptionLabel;
private Text rollbackOnFailureLabel;
private Link outputLink;
private volatile boolean stackInStableState;
private Thread autoRefreshThread;
private StackEventsTable stackEventsTable;
private StackOutputsTable stackOutputsTable;
private StackParametersTable stackParametersTable;
private StackResourcesTable stackResourcesTable;
private RefreshAction refreshAction;
@Override
public void doSave(IProgressMonitor monitor) {}
@Override
public void doSaveAs() {}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
setPartName(input.getName());
this.stackEditorInput = (StackEditorInput)input;
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void createPartControl(Composite parent) {
FormToolkit toolkit = new FormToolkit(Display.getDefault());
ScrolledForm form = new ScrolledForm(parent, SWT.V_SCROLL | SWT.H_SCROLL);
form.setExpandHorizontal(true);
form.setExpandVertical(true);
form.setBackground(toolkit.getColors().getBackground());
form.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
form.setFont(JFaceResources.getHeaderFont());
form.setText(getFormTitle());
toolkit.decorateFormHeading(form.getForm());
form.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_STACK));
form.getBody().setLayout(new GridLayout());
createSummarySection(form.getBody(), toolkit);
createTabsSection(form.getBody(), toolkit);
refreshAction = new RefreshAction();
form.getToolBarManager().add(refreshAction);
form.getToolBarManager().update(true);
new LoadStackSummaryThread().start();
if (stackEditorInput.isAutoRefresh()) {
autoRefreshThread = new Thread(new Runnable() {
@Override
public void run() {
while (!isStackInStableState()) {
try {
Thread.sleep(5 * 1000);
refreshAction.run();
} catch (InterruptedException e) {
// When exception happens, we leave this thread.
return;
}
}
}
});
autoRefreshThread.start();
}
}
private String getFormTitle() {
String formTitle = stackEditorInput.getName();
Region region = RegionUtils.getRegionByEndpoint(stackEditorInput.getRegionEndpoint());
if (region != null) {
formTitle += " - " + region.getName();
} else {
formTitle += " - " + stackEditorInput.getRegionEndpoint();
}
return formTitle;
}
private void createSummarySection(Composite parent, FormToolkit toolkit) {
GridDataFactory gridDataFactory = GridDataFactory.swtDefaults()
.align(SWT.FILL, SWT.TOP).grab(true, false).minSize(200, SWT.DEFAULT).hint(200, SWT.DEFAULT);
Composite composite = toolkit.createComposite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
composite.setLayout(new GridLayout(4, false));
toolkit.createLabel(composite, "Stack Name:");
stackNameLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(stackNameLabel);
toolkit.createLabel(composite, "Created:");
createdLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(createdLabel);
toolkit.createLabel(composite, "Status:");
statusLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(statusLabel);
toolkit.createLabel(composite, "Create Timeout:");
createTimeoutLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(createTimeoutLabel);
toolkit.createLabel(composite, "Status Reason:");
statusReasonLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(statusReasonLabel);
toolkit.createLabel(composite, "Last Updated:");
lastUpdatedLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(lastUpdatedLabel);
toolkit.createLabel(composite, "Rollback on Failure:");
rollbackOnFailureLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE);
toolkit.createLabel(composite, "");
toolkit.createLabel(composite, "");
Label l = toolkit.createLabel(composite, "Description:");
gridDataFactory.copy().hint(100, SWT.DEFAULT).minSize(1, SWT.DEFAULT).align(SWT.LEFT, SWT.TOP).grab(false, false).applyTo(l);
descriptionLabel = new Text(composite, SWT.READ_ONLY | SWT.NONE | SWT.MULTI | SWT.WRAP);
gridDataFactory.copy().span(3, 1).applyTo(descriptionLabel);
Label outputL = toolkit.createLabel(composite, "Output:");
gridDataFactory.copy().hint(100, SWT.DEFAULT).minSize(1, SWT.DEFAULT).align(SWT.LEFT, SWT.TOP).grab(false, false).applyTo(outputL);
outputLink = new Link(composite, SWT.READ_ONLY | SWT.NONE | SWT.MULTI | SWT.WRAP);
outputLink.addListener(SWT.Selection, new WebLinkListener());
gridDataFactory.copy().span(3, 1).applyTo(outputLink);
}
private void createTabsSection(Composite parent, FormToolkit toolkit) {
Composite tabsSection = toolkit.createComposite(parent, SWT.NONE);
tabsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
tabsSection.setLayout(new FillLayout());
TabFolder tabFolder = new TabFolder (tabsSection, SWT.BORDER);
Rectangle clientArea = parent.getClientArea();
tabFolder.setLocation(clientArea.x, clientArea.y);
TabItem eventsTab = new TabItem(tabFolder, SWT.NONE);
eventsTab.setText("Events");
stackEventsTable = new StackEventsTable(tabFolder, toolkit, stackEditorInput);
eventsTab.setControl(stackEventsTable);
TabItem resourcesTab = new TabItem(tabFolder, SWT.NONE);
resourcesTab.setText("Resources");
stackResourcesTable = new StackResourcesTable(tabFolder, toolkit, stackEditorInput);
resourcesTab.setControl(stackResourcesTable);
TabItem parametersTab = new TabItem(tabFolder, SWT.NONE);
parametersTab.setText("Parameters");
stackParametersTable = new StackParametersTable(tabFolder, toolkit);
parametersTab.setControl(stackParametersTable);
TabItem outputsTab = new TabItem(tabFolder, SWT.NONE);
outputsTab.setText("Outputs");
stackOutputsTable = new StackOutputsTable(tabFolder, toolkit);
outputsTab.setControl(stackOutputsTable);
tabFolder.pack();
}
@Override
public void setFocus() {}
@Override
public void dispose() {
super.dispose();
if (autoRefreshThread != null) {
autoRefreshThread.interrupt();
}
}
private AmazonCloudFormation getClient() {
AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(stackEditorInput.getAccountId());
return clientFactory.getCloudFormationClientByEndpoint(stackEditorInput.getRegionEndpoint());
}
public boolean isStackInStableState() {
return stackInStableState;
}
private void setStackInStableState(boolean stackInStableState) {
this.stackInStableState = stackInStableState;
}
private class LoadStackSummaryThread extends Thread {
private Stack describeStack() {
DescribeStacksRequest request = new DescribeStacksRequest().withStackName(stackEditorInput.getStackName());
List<Stack> stacks = getClient().describeStacks(request).getStacks();
if (stacks.size() == 0) {
return new Stack();
} else if (stacks.size() > 1) {
throw new RuntimeException("Unexpected number of stacks returned");
}
return stacks.get(0);
}
private String createRestApiProdLink(String restApi, String region, String restApiProdStage) {
return String.format("https://%s.execute-api.%s.amazonaws.com/%s", restApi, region, restApiProdStage);
}
@Override
public void run() {
try {
final Stack stack = describeStack();
setStackInStableState(STABLE_STATE_LIST.contains(stack.getStackStatus()));
DescribeStackResourcesRequest request = new DescribeStackResourcesRequest().withStackName(stackEditorInput.getStackName());
final List<StackResource> stackResources = getClient().describeStackResources(request).getStackResources();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
descriptionLabel.setText(valueOrDefault(stack.getDescription(), ""));
lastUpdatedLabel.setText(valueOrDefault(stack.getLastUpdatedTime(), "N/A"));
stackNameLabel.setText(stack.getStackName());
statusLabel.setText(stack.getStackStatus());
statusReasonLabel.setText(valueOrDefault(stack.getStackStatusReason(), ""));
createdLabel.setText(valueOrDefault(stack.getCreationTime(), "N/A"));
createTimeoutLabel.setText(valueOrDefault(stack.getTimeoutInMinutes(), "N/A"));
Boolean disableRollback = stack.getDisableRollback();
if (disableRollback != null) disableRollback = !disableRollback;
rollbackOnFailureLabel.setText(booleanYesOrNo(disableRollback));
String serverlessRestApi = null;
String serverlessRestApiProdStage = null;
for (StackResource resource : stackResources) {
if (resource.getLogicalResourceId().equals(SERVERLESS_REST_API)) {
serverlessRestApi = resource.getPhysicalResourceId();
}
if (resource.getLogicalResourceId().equals(SERVERLESS_REST_API_PROD_STAGE)) {
serverlessRestApiProdStage = resource.getPhysicalResourceId();
}
}
if (serverlessRestApi != null && serverlessRestApiProdStage != null) {
String region = RegionUtils.getRegionByEndpoint(stackEditorInput.getRegionEndpoint()).getId();
outputLink.setText(createLinkText(createRestApiProdLink(
serverlessRestApi, region, serverlessRestApiProdStage)));
}
stackNameLabel.getParent().layout();
stackNameLabel.getParent().getParent().layout(true);
stackOutputsTable.setStackOutputs(stack.getOutputs());
stackParametersTable.setStackParameters(stack.getParameters());
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, CloudFormationPlugin.PLUGIN_ID, "Unable to describe stack " + stackEditorInput.getStackName(), e);
StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW);
}
}
private String booleanYesOrNo(Boolean b) {
if (b == null) return "";
if (b == true) return "Yes";
else return "No";
}
private String valueOrDefault(Date date, String defaultValue) {
if (date != null) return date.toString();
else return defaultValue;
}
private String valueOrDefault(Integer integer, String defaultValue) {
if (integer != null) return integer.toString();
else return defaultValue;
}
private String valueOrDefault(String value, String defaultValue) {
if (value != null) return value;
else return defaultValue;
}
}
private class RefreshAction extends Action {
public RefreshAction() {
this.setText("Refresh");
this.setToolTipText("Refresh stack information");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH));
}
@Override
public void run() {
new LoadStackSummaryThread().start();
stackEventsTable.refresh();
stackResourcesTable.refresh();
}
}
private String createLinkText(String url) {
return String.format("<a href=\"%s\">%s</a>", url, url);
}
}
| 8,050 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/StackResourcesTable.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreePathContentProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.ec2.ui.views.instances.InstanceSelectionTable;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.DescribeStackResourcesRequest;
import com.amazonaws.services.cloudformation.model.StackResource;
class StackResourcesTable extends Composite {
private TreeViewer viewer;
private final StackEditorInput stackEditorInput;
private InstanceSelectionTable instanceSelectionTable;
public StackResourcesTable(Composite parent, FormToolkit toolkit, StackEditorInput stackEditorInput) {
super(parent, SWT.NONE);
this.stackEditorInput = stackEditorInput;
this.setLayout(new GridLayout());
instanceSelectionTable = new InstanceSelectionTable(this);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.minimumHeight = 200;
gridData.heightHint = 200;
instanceSelectionTable.setLayoutData(gridData);
Region region = RegionUtils.getRegionByEndpoint(stackEditorInput.getRegionEndpoint());
if (region == null) {
Status status = new Status(IStatus.WARNING, CloudFormationPlugin.PLUGIN_ID, "Unable to determine region from endpoint " + stackEditorInput.getRegionEndpoint());
StatusManager.getManager().handle(status, StatusManager.LOG);
} else {
String endpoint = region.getServiceEndpoint(ServiceAbbreviations.EC2);
if (endpoint != null) {
instanceSelectionTable.setEc2RegionOverride(region);
instanceSelectionTable.refreshData();
}
if (endpoint == null) {
Status status = new Status(IStatus.ERROR, CloudFormationPlugin.PLUGIN_ID, "Unable to determine EC2 endpoint for region " + region.getId());
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
Composite composite = toolkit.createComposite(this);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TreeColumnLayout tableColumnLayout = new TreeColumnLayout();
composite.setLayout(tableColumnLayout);
StackResourcesContentProvider contentProvider = new StackResourcesContentProvider();
StackResourcesLabelProvider labelProvider = new StackResourcesLabelProvider();
viewer = new TreeViewer(composite, SWT.BORDER | SWT.MULTI);
viewer.getTree().setLinesVisible(true);
viewer.getTree().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTree());
refresh();
}
public void refresh() {
new LoadStackResourcesThread().start();
instanceSelectionTable.refreshData();
}
private AmazonCloudFormation getClient() {
AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(stackEditorInput.getAccountId());
return clientFactory.getCloudFormationClientByEndpoint(stackEditorInput.getRegionEndpoint());
}
private class LoadStackResourcesThread extends Thread {
@Override
public void run() {
try {
DescribeStackResourcesRequest request = new DescribeStackResourcesRequest().withStackName(stackEditorInput.getStackName());
final List<StackResource> stackResources = getClient().describeStackResources(request).getStackResources();
List<String> instances = new LinkedList<>();
for (StackResource resource : stackResources) {
if (resource.getResourceType().equalsIgnoreCase("AWS::EC2::Instance")) {
instances.add(resource.getPhysicalResourceId());
}
}
instanceSelectionTable.setInstancesToList(instances);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(stackResources.toArray(new StackResource[stackResources.size()]));
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, CloudFormationPlugin.PLUGIN_ID, "Unable to describe resources for stack " + stackEditorInput.getStackName(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
private final class StackResourcesContentProvider implements ITreePathContentProvider {
private StackResource[] resources;
@Override
public void dispose() {}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof StackResource[]) {
resources = (StackResource[])newInput;
} else {
resources = new StackResource[0];
}
}
@Override
public Object[] getElements(Object inputElement) {
return resources;
}
@Override
public Object[] getChildren(TreePath parentPath) {
return null;
}
@Override
public boolean hasChildren(TreePath path) {
return false;
}
@Override
public TreePath[] getParents(Object element) {
return new TreePath[0];
}
}
private final class StackResourcesLabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public void removeListener(ILabelProviderListener listener) {}
@Override
public void dispose() {}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof StackResource == false) return "";
StackResource resource = (StackResource)element;
switch (columnIndex) {
case 0: return resource.getLogicalResourceId();
case 1: return resource.getPhysicalResourceId();
case 2: return resource.getResourceType();
case 3: return resource.getResourceStatus();
case 4: return resource.getResourceStatusReason();
default: return "";
}
}
}
private void createColumns(TreeColumnLayout columnLayout, Tree tree) {
createColumn(tree, columnLayout, "Logical ID");
createColumn(tree, columnLayout, "Physical ID");
createColumn(tree, columnLayout, "Type");
createColumn(tree, columnLayout, "Status");
createColumn(tree, columnLayout, "Status Reason");
}
private TreeColumn createColumn(Tree tree, TreeColumnLayout columnLayout, String text) {
TreeColumn column = new TreeColumn(tree, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
} | 8,051 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/CloudFormationLabelProvider.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider;
import com.amazonaws.eclipse.explorer.cloudformation.CloudFormationContentProvider.CloudFormationRootElement;
public class CloudFormationLabelProvider extends ExplorerNodeLabelProvider {
@Override
public String getText(Object element) {
if (element instanceof CloudFormationRootElement) return "AWS CloudFormation";
return getExplorerNodeText(element);
}
@Override
public Image getDefaultImage(Object element) {
if (element instanceof CloudFormationRootElement) {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_CLOUDFORMATION_SERVICE);
} else {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_STACK);
}
}
}
| 8,052 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/wizard/CreateStackWizard.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation.wizard;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.BrowserUtils;
import com.amazonaws.eclipse.core.model.KeyValueSetDataModel.Pair;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizardDataModel.Mode;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.CancelUpdateStackRequest;
import com.amazonaws.services.cloudformation.model.CreateStackRequest;
import com.amazonaws.services.cloudformation.model.EstimateTemplateCostRequest;
import com.amazonaws.services.cloudformation.model.EstimateTemplateCostResult;
import com.amazonaws.services.cloudformation.model.Parameter;
import com.amazonaws.services.cloudformation.model.Tag;
import com.amazonaws.services.cloudformation.model.TemplateParameter;
import com.amazonaws.services.cloudformation.model.UpdateStackRequest;
/**
* Wizard to create a new cloud formation stack
*/
public class CreateStackWizard extends Wizard {
private CreateStackWizardDataModel dataModel;
private CreateStackWizardFirstPage firstPage;
private CreateStackWizardSecondPage secondPage;
private CreateStackWizardThirdPage thirdPage;
public CreateStackWizard() {
this(null, null, null);
}
public CreateStackWizard(String stackName, Mode mode) {
this(stackName, null, mode);
}
public CreateStackWizard(IPath filePath, Mode mode) {
this(null, filePath, mode);
}
public CreateStackWizard(String stackName, IPath filePath, Mode mode) {
setNeedsProgressMonitor(false);
if ( mode == Mode.Update ) {
setWindowTitle("Update Cloud Formation Stack");
} else if (mode == Mode.Create) {
setWindowTitle("Create New Cloud Formation Stack");
} else {
setWindowTitle("Estimate the Cost of the Template");
}
setDefaultPageImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry()
.getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO));
dataModel = new CreateStackWizardDataModel();
dataModel.setStackName(stackName);
if (filePath != null) {
dataModel.setUsePreselectedTemplateFile(true);
dataModel.setUseTemplateFile(true);
dataModel.setTemplateFile(filePath.toFile().getAbsolutePath());
}
if (mode != null) {
dataModel.setMode(mode);
}
}
@Override
public boolean performFinish() {
final CreateStackRequest createStackRequest = getCreateStackRequest();
new Job("Creating stack") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
AmazonCloudFormation cloudFormationClient = AwsToolkitCore.getClientFactory()
.getCloudFormationClient();
if ( dataModel.getMode() == Mode.Create ) {
cloudFormationClient.createStack(createStackRequest);
} else if (dataModel.getMode() == Mode.Update ){
cloudFormationClient.updateStack(createUpdateStackRequest(createStackRequest));
}
if (dataModel.getMode() == Mode.EstimateCost) {
EstimateTemplateCostRequest estimateTemplateCostRequest = createEstimateTemplateCostRequest(createStackRequest);
EstimateTemplateCostResult estimateTemplateCostResult = cloudFormationClient.estimateTemplateCost(estimateTemplateCostRequest);
String url = estimateTemplateCostResult.getUrl();
BrowserUtils.openExternalBrowser(url);
} else {
// Let the user have the time to cancel the update
// operationin Progress.
Thread.sleep(1000 * 30);
}
return Status.OK_STATUS;
} catch ( Exception e ) {
return new Status(Status.ERROR, CloudFormationPlugin.PLUGIN_ID, "Failed to " +
((dataModel.getMode() == Mode.Create) ? "create" : "update") +
" stack", e);
}
}
@Override
protected void canceling() {
try {
AmazonCloudFormation cloudFormationClient = AwsToolkitCore.getClientFactory()
.getCloudFormationClient();
cloudFormationClient.cancelUpdateStack(new CancelUpdateStackRequest().withStackName(dataModel.getStackName()));
} catch ( Exception e ) {
CloudFormationPlugin.getDefault().logError("Couldn't cancel the stack update", e);
StatusManager.getManager().handle( new Status(Status.ERROR, CloudFormationPlugin.PLUGIN_ID,
"Couldn't cancel the stack update:", e));
}
}
}.schedule();
return true;
}
private UpdateStackRequest createUpdateStackRequest(CreateStackRequest createStackRequest) {
UpdateStackRequest rq = new UpdateStackRequest();
rq.setStackName(createStackRequest.getStackName());
rq.setCapabilities(createStackRequest.getCapabilities());
rq.setParameters(createStackRequest.getParameters());
rq.setTemplateBody(createStackRequest.getTemplateBody());
rq.setTemplateURL(createStackRequest.getTemplateURL());
rq.setTags(createStackRequest.getTags());
return rq;
}
private EstimateTemplateCostRequest createEstimateTemplateCostRequest(CreateStackRequest createStackRequest) {
EstimateTemplateCostRequest rq = new EstimateTemplateCostRequest();
rq.setParameters(createStackRequest.getParameters());
rq.setTemplateBody(createStackRequest.getTemplateBody());
rq.setTemplateURL(createStackRequest.getTemplateURL());
return rq;
}
private boolean needsSecondPage = true;
protected void setNeedsSecondPage(boolean needsSecondPage) {
this.needsSecondPage = needsSecondPage;
getContainer().updateButtons();
}
public boolean needsSecondPage() {
return needsSecondPage;
}
public boolean needsThirdPage() {
return Mode.EstimateCost != dataModel.getMode();
}
private CreateStackRequest getCreateStackRequest() {
CreateStackRequest rq = new CreateStackRequest();
rq.setDisableRollback(!dataModel.getRollbackOnFailure());
if ( dataModel.getNotifyWithSNS() ) {
List<String> arns = new ArrayList<>();
arns.add(dataModel.getSnsTopicArn());
rq.setNotificationARNs(arns);
}
rq.setStackName(dataModel.getStackName());
if ( dataModel.getUseTemplateFile() ) {
rq.setTemplateBody(dataModel.getTemplateBody());
} else {
rq.setTemplateURL(dataModel.getTemplateUrl());
}
if ( rq.getTimeoutInMinutes() != null && rq.getTimeoutInMinutes() > 0 ) {
rq.setTimeoutInMinutes(dataModel.getTimeoutMinutes());
}
List<Parameter> params = new ArrayList<>();
for ( TemplateParameter parameter : dataModel.getParametersDataModel().getTemplateParameters() ) {
String value = (String) dataModel.getParametersDataModel().getParameterValues().get(parameter.getParameterKey());
if ( value != null && value.length() > 0 ) {
params.add(new Parameter().withParameterKey(parameter.getParameterKey()).withParameterValue(value));
}
}
rq.setParameters(params);
rq.setCapabilities(dataModel.getRequiredCapabilities());
if (dataModel.getTagModel().getPairSet() != null) {
List<Tag> tags = new ArrayList<>(dataModel.getTagModel().getPairSet().size());
for (Pair pair : dataModel.getTagModel().getPairSet()) {
tags.add(new Tag().withKey(pair.getKey()).withValue(pair.getValue()));
}
rq.setTags(tags);
}
return rq;
}
@Override
public void addPages() {
if (firstPage == null) {
firstPage = new CreateStackWizardFirstPage(this);
}
if (secondPage == null) {
secondPage = new CreateStackWizardSecondPage(this.getDataModel());
}
addPage(firstPage);
addPage(secondPage);
if (Mode.EstimateCost != dataModel.getMode()) {
thirdPage = new CreateStackWizardThirdPage(this.getDataModel());
addPage(thirdPage);
}
}
CreateStackWizardDataModel getDataModel() {
return dataModel;
}
@Override
public int getPageCount() {
return (needsSecondPage() ? 2 : 1) + (needsThirdPage() ? 1 : 0);
}
@Override
public IWizardPage[] getPages() {
if (needsSecondPage()) {
return super.getPages();
} else {
List<IWizardPage> wizardPages = new ArrayList<>(super.getPageCount());
for (IWizardPage wizardPage : super.getPages()) {
if (wizardPage instanceof CreateStackWizardSecondPage) {
continue;
}
wizardPages.add(wizardPage);
}
return wizardPages.toArray(new IWizardPage[0]);
}
}
@Override
public IWizardPage getNextPage(IWizardPage currentPage) {
if (currentPage == firstPage && needsSecondPage()) {
return secondPage;
}
return thirdPage;
}
/**
* There's no second page in some cases.
*/
@Override
public boolean canFinish() {
if (needsSecondPage())
return super.canFinish();
else
return getPages()[0].isPageComplete();
}
}
| 8,053 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/wizard/CreateStackWizardDataModel.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation.wizard;
import static com.amazonaws.eclipse.cloudformation.CloudFormationConstants.MAX_ALLOWED_TAG_AMOUNT;
import java.util.ArrayList;
import java.util.Collection;
import com.amazonaws.eclipse.cloudformation.model.ParametersDataModel;
import com.amazonaws.eclipse.core.model.KeyValueSetDataModel;
import com.amazonaws.eclipse.core.model.KeyValueSetDataModel.Pair;
/**
* Data model for creating a new stack
*/
public class CreateStackWizardDataModel {
private String stackName;
private String templateUrl;
private String templateFile;
private Boolean useTemplateFile;
private Boolean useTemplateUrl;
private String snsTopicArn;
private Boolean notifyWithSNS = false;
private Integer timeoutMinutes;
private Boolean rollbackOnFailure = true;
private Collection<String> requiredCapabilities;
// for use only with file templates, to avoid processing the file twice
private String templateBody;
private boolean usePreselectedTemplateFile;
private final KeyValueSetDataModel tagModel = new KeyValueSetDataModel(MAX_ALLOWED_TAG_AMOUNT, new ArrayList<Pair>(MAX_ALLOWED_TAG_AMOUNT));
private Mode mode = Mode.Create;
private final ParametersDataModel parametersDataModel = new ParametersDataModel();
public static enum Mode {
Create, Update, EstimateCost
};
public String getStackName() {
return stackName;
}
public void setStackName(String stackName) {
this.stackName = stackName;
}
public String getTemplateUrl() {
return templateUrl;
}
public void setTemplateUrl(String templateUrl) {
this.templateUrl = templateUrl;
}
public String getTemplateFile() {
return templateFile;
}
public void setTemplateFile(String templateFile) {
this.templateFile = templateFile;
}
public Boolean getUseTemplateFile() {
return useTemplateFile;
}
public void setUseTemplateFile(Boolean useTemplateFile) {
this.useTemplateFile = useTemplateFile;
}
public Boolean getUseTemplateUrl() {
return useTemplateUrl;
}
public void setUseTemplateUrl(Boolean useTemplateUrl) {
this.useTemplateUrl = useTemplateUrl;
}
public String getSnsTopicArn() {
return snsTopicArn;
}
public void setSnsTopicArn(String snsTopicArn) {
this.snsTopicArn = snsTopicArn;
}
public Boolean getNotifyWithSNS() {
return notifyWithSNS;
}
public void setNotifyWithSNS(Boolean notifyWithSNS) {
this.notifyWithSNS = notifyWithSNS;
}
public Integer getTimeoutMinutes() {
return timeoutMinutes;
}
public void setTimeoutMinutes(Integer timeoutMinutes) {
this.timeoutMinutes = timeoutMinutes;
}
public Boolean getRollbackOnFailure() {
return rollbackOnFailure;
}
public void setRollbackOnFailure(Boolean rollbackOnFailure) {
this.rollbackOnFailure = rollbackOnFailure;
}
public String getTemplateBody() {
return templateBody;
}
public void setTemplateBody(String templateBody) {
this.templateBody = templateBody;
}
public Collection<String> getRequiredCapabilities() {
return requiredCapabilities;
}
public void setRequiredCapabilities(Collection<String> requiredCapabilities) {
this.requiredCapabilities = requiredCapabilities;
}
public boolean isUsePreselectedTemplateFile() {
return usePreselectedTemplateFile;
}
public void setUsePreselectedTemplateFile(boolean usePreselectedTemplateFile) {
this.usePreselectedTemplateFile = usePreselectedTemplateFile;
}
public KeyValueSetDataModel getTagModel() {
return tagModel;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode mode) {
this.mode = mode;
}
public ParametersDataModel getParametersDataModel() {
return parametersDataModel;
}
}
| 8,054 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/wizard/CreateStackWizardSecondPage.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation.wizard;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.ChangeEvent;
import org.eclipse.core.databinding.observable.IChangeListener;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import com.amazonaws.eclipse.cloudformation.ui.ParametersComposite;
/**
* The second page in the create wizard second page
*/
public class CreateStackWizardSecondPage extends WizardPage {
private final CreateStackWizardDataModel dataModel;
private DataBindingContext bindingContext;
private AggregateValidationStatus aggregateValidationStatus;
private static final String OK_MESSAGE = "Provide values for template parameters.";
private Composite comp;
private ScrolledComposite scrolledComp;
protected CreateStackWizardSecondPage(CreateStackWizardDataModel dataModel) {
super("Fill in stack template parameters");
setTitle("Fill in stack template parameters");
setDescription(OK_MESSAGE);
this.dataModel = dataModel;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets
* .Composite)
*/
@Override
public void createControl(final Composite parent) {
scrolledComp = new ScrolledComposite(parent, SWT.V_SCROLL);
scrolledComp.setExpandHorizontal(true);
scrolledComp.setExpandVertical(true);
GridDataFactory.fillDefaults().grab(true, true).applyTo(scrolledComp);
comp = new Composite(scrolledComp, SWT.None);
GridDataFactory.fillDefaults().grab(true, true).applyTo(comp);
GridLayoutFactory.fillDefaults().numColumns(1).applyTo(comp);
scrolledComp.setContent(comp);
scrolledComp.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
if (comp != null) {
Rectangle r = scrolledComp.getClientArea();
scrolledComp.setMinSize(comp.computeSize(r.width, SWT.DEFAULT));
}
}
});
setControl(scrolledComp);
}
private void createContents() {
for ( Control c : comp.getChildren() ) {
c.dispose();
}
bindingContext = new DataBindingContext();
aggregateValidationStatus = new AggregateValidationStatus(bindingContext,
AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
populateValidationStatus();
}
});
new ParametersComposite(comp, dataModel.getParametersDataModel(), bindingContext);
comp.layout();
Rectangle r = scrolledComp.getClientArea();
scrolledComp.setMinSize(comp.computeSize(r.width, SWT.DEFAULT));
}
@Override
public void setVisible(boolean visible) {
if ( visible ) {
createContents();
}
super.setVisible(visible);
}
private void populateValidationStatus() {
Object value = aggregateValidationStatus.getValue();
if ( value instanceof IStatus == false )
return;
IStatus status = (IStatus) value;
if ( status.isOK() ) {
setErrorMessage(null);
setMessage(OK_MESSAGE, Status.OK);
} else if ( status.getSeverity() == Status.WARNING ) {
setErrorMessage(null);
setMessage(status.getMessage(), Status.WARNING);
} else if ( status.getSeverity() == Status.ERROR ) {
setErrorMessage(status.getMessage());
}
setPageComplete(status.isOK());
}
}
| 8,055 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/wizard/CreateStackWizardFirstPage.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation.wizard;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.ValidationStatusProvider;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.conversion.IConverter;
import org.eclipse.core.databinding.observable.ChangeEvent;
import org.eclipse.core.databinding.observable.IChangeListener;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.observable.value.WritableValue;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.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.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.cloudformation.CloudFormationUtils;
import com.amazonaws.eclipse.cloudformation.CloudFormationUtils.StackSummaryConverter;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.ui.CancelableThread;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.databinding.ChainValidator;
import com.amazonaws.eclipse.databinding.DecorationChangeListener;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizardDataModel.Mode;
import com.amazonaws.eclipse.explorer.sns.CreateTopicDialog;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.DescribeStacksRequest;
import com.amazonaws.services.cloudformation.model.DescribeStacksResult;
import com.amazonaws.services.cloudformation.model.Parameter;
import com.amazonaws.services.cloudformation.model.Stack;
import com.amazonaws.services.cloudformation.model.StackSummary;
import com.amazonaws.services.cloudformation.model.TemplateParameter;
import com.amazonaws.services.cloudformation.model.ValidateTemplateRequest;
import com.amazonaws.services.cloudformation.model.ValidateTemplateResult;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.ListTopicsResult;
import com.amazonaws.services.sns.model.Topic;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* The first page of the stack creation wizard, which prompts for a name and
* template.
*/
class CreateStackWizardFirstPage extends WizardPage {
private static final String LOADING_STACKS = "Loading stacks...";
private static final String OK_MESSAGE = "Provide a name and a template for your new stack.";
private static final String ESTIMATE_COST_OK_MESSAGE = "Provide a template to esitmate the cost";
private static final String VALIDATING = "validating";
private static final String INVALID = "invalid";
private static final String VALID = "valid";
/*
* Data model
*/
private IObservableValue stackName;
private IObservableValue templateUrl;
private IObservableValue templateFile;
private IObservableValue useTemplateFile;
private IObservableValue useTemplateUrl;
private IObservableValue snsTopicArn;
private IObservableValue notifyWithSNS;
private IObservableValue timeoutMinutes;
private IObservableValue rollbackOnFailure;
private IObservableValue templateValidated = new WritableValue();
private final DataBindingContext bindingContext = new DataBindingContext();
private boolean complete = false;
private ValidateTemplateThread validateTemplateThread;
private LoadStackNamesThread loadStackNamesThread;
private Exception templateValidationException;
private Text fileTemplateText;
private Text templateURLText;
private CreateStackWizard wizard;
protected CreateStackWizardFirstPage(CreateStackWizard createStackWizard) {
super("");
wizard = createStackWizard;
if (wizard.getDataModel().getMode() == Mode.EstimateCost) {
setMessage(ESTIMATE_COST_OK_MESSAGE);
} else {
setMessage(OK_MESSAGE);
}
stackName = PojoObservables.observeValue(wizard.getDataModel(), "stackName");
templateUrl = PojoObservables.observeValue(wizard.getDataModel(), "templateUrl");
templateFile = PojoObservables.observeValue(wizard.getDataModel(), "templateFile");
useTemplateFile = PojoObservables.observeValue(wizard.getDataModel(), "useTemplateFile");
useTemplateUrl = PojoObservables.observeValue(wizard.getDataModel(), "useTemplateUrl");
notifyWithSNS = PojoObservables.observeValue(wizard.getDataModel(), "notifyWithSNS");
snsTopicArn = PojoObservables.observeValue(wizard.getDataModel(), "snsTopicArn");
timeoutMinutes = PojoObservables.observeValue(wizard.getDataModel(), "timeoutMinutes");
rollbackOnFailure = PojoObservables.observeValue(wizard.getDataModel(), "rollbackOnFailure");
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt
* .widgets.Composite)
*/
@Override
public void createControl(Composite parent) {
final Composite comp = new Composite(parent, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, true).applyTo(comp);
GridLayoutFactory.fillDefaults().numColumns(3).applyTo(comp);
// Unfortunately, we have to manually adjust for field decorations
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(
FieldDecorationRegistry.DEC_ERROR);
int fieldDecorationWidth = fieldDecoration.getImage().getBounds().width;
if (wizard.getDataModel().getMode() != Mode.EstimateCost) {
createStackNameControl(comp, fieldDecorationWidth);
}
createTemplateSelectionControl(comp, fieldDecorationWidth);
// Some fields are only for creation, not update
if ( wizard.getDataModel().getMode() == Mode.Create ) {
createSNSTopicControl(comp, fieldDecorationWidth);
createTimeoutControl(comp);
createRollbackControl(comp);
}
setUpValidation(comp);
// Set initial values for radio buttons
useTemplateFile.setValue(true);
templateValidated.setValue(null);
// If we already have a file template filled in, validate it
if ( wizard.getDataModel().isUsePreselectedTemplateFile() ) {
validateTemplateFile((String) templateFile.getValue());
}
setControl(comp);
}
private void createStackNameControl(final Composite comp, int fieldDecorationWidth) {
// Whether the user already set the stack name.
boolean stackNameExists = false;
new Label(comp, SWT.READ_ONLY).setText("Stack Name: ");
Control stackNameControl = null;
if ( wizard.getDataModel().getMode() == Mode.Create ) {
Text stackNameText = new Text(comp, SWT.BORDER);
bindingContext.bindValue(SWTObservables.observeText(stackNameText, SWT.Modify), stackName)
.updateTargetToModel();
stackNameControl = stackNameText;
} else {
Combo combo = new Combo(comp, SWT.READ_ONLY | SWT.DROP_DOWN);
if (stackName.getValue() != null) {
combo.setItems(new String[] { (String)stackName.getValue() });
stackNameExists = true;
} else {
combo.setItems(new String[] { LOADING_STACKS });
}
combo.select(0);
bindingContext.bindValue(SWTObservables.observeSelection(combo), stackName).updateTargetToModel();
stackNameControl = combo;
stackName.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
if ( (Boolean) useTemplateFile.getValue() ) {
validateTemplateFile((String) templateFile.getValue());
} else {
validateTemplateUrl((String) templateUrl.getValue());
}
}
});
if (!stackNameExists) {
loadStackNames(combo);
}
}
GridDataFactory.fillDefaults().grab(true, false).span(2, 1).indent(fieldDecorationWidth, 0)
.applyTo(stackNameControl);
ChainValidator<String> stackNameValidationStatusProvider = new ChainValidator<>(stackName,
new NotEmptyValidator("Please provide a stack name"));
bindingContext.addValidationStatusProvider(stackNameValidationStatusProvider);
addStatusDecorator(stackNameControl, stackNameValidationStatusProvider);
}
/**
* Loads the names of all the stacks asynchronously.
*/
private void loadStackNames(Combo combo) {
CancelableThread.cancelThread(loadStackNamesThread);
templateValidated.setValue(VALIDATING);
loadStackNamesThread = new LoadStackNamesThread(combo);
loadStackNamesThread.start();
}
private final class LoadStackNamesThread extends CancelableThread {
private Combo combo;
private LoadStackNamesThread(Combo combo) {
super();
this.combo = combo;
}
@Override
public void run() {
final List<String> stackNames = CloudFormationUtils.listExistingStacks(
new StackSummaryConverter<String>() {
@Override
public String convert(StackSummary stack) {
return stack.getStackName();
}
});
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
try {
synchronized ( this ) {
if (!isCanceled()) {
combo.setItems(stackNames.toArray(new String[stackNames.size()]));
combo.select(0);
templateValidated.setValue(VALID);
}
}
} finally {
setRunning(false);
}
}
});
}
}
private void createTemplateSelectionControl(final Composite comp, int fieldDecorationWidth) {
Group stackTemplateSourceGroup = new Group(comp, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, false).span(3, 1).indent(fieldDecorationWidth, 0)
.applyTo(stackTemplateSourceGroup);
GridLayoutFactory.fillDefaults().numColumns(3).applyTo(stackTemplateSourceGroup);
stackTemplateSourceGroup.setText("Stack Template Source:");
createTemplateFileControl(stackTemplateSourceGroup, fieldDecorationWidth);
createTemplateUrlControl(stackTemplateSourceGroup, fieldDecorationWidth);
}
private void createTemplateUrlControl(Group stackTemplateSourceGroup, int fieldDecorationWidth) {
final Button templateUrlOption = new Button(stackTemplateSourceGroup, SWT.RADIO);
templateUrlOption.setText("Template URL: ");
templateURLText = new Text(stackTemplateSourceGroup, SWT.BORDER);
templateURLText.setEnabled(false);
GridDataFactory.fillDefaults().grab(true, false).indent(fieldDecorationWidth, 0).applyTo(templateURLText);
Link link = new Link(stackTemplateSourceGroup, SWT.None);
// TODO: this should really live in the regions file, not hardcoded here
Region currentRegion = RegionUtils.getCurrentRegion();
final String sampleUrl = String.format(
"http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-sample-templates-%s.html",
currentRegion.getId());
link.setText("<a href=\"" +
sampleUrl +
"\">Browse for samples</a>");
link.addListener(SWT.Selection, new WebLinkListener());
bindingContext.bindValue(SWTObservables.observeText(templateURLText, SWT.Modify), templateUrl)
.updateTargetToModel();
bindingContext.bindValue(SWTObservables.observeSelection(templateUrlOption), useTemplateUrl)
.updateTargetToModel();
ChainValidator<String> templateUrlValidationStatusProvider = new ChainValidator<>(templateUrl,
useTemplateUrl, new NotEmptyValidator("Please provide a valid URL for your template"));
bindingContext.addValidationStatusProvider(templateUrlValidationStatusProvider);
addStatusDecorator(templateURLText, templateUrlValidationStatusProvider);
templateUrlOption.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean selected = templateUrlOption.getSelection();
templateURLText.setEnabled(selected);
}
});
}
private void createTemplateFileControl(Group stackTemplateSourceGroup, int fieldDecorationWidth) {
Button fileTemplateOption = new Button(stackTemplateSourceGroup, SWT.RADIO);
fileTemplateOption.setText("Template File: ");
fileTemplateOption.setSelection(true);
fileTemplateText = new Text(stackTemplateSourceGroup, SWT.BORDER | SWT.READ_ONLY);
GridDataFactory.fillDefaults().grab(true, false).indent(fieldDecorationWidth, 0).applyTo(fileTemplateText);
Button browseButton = new Button(stackTemplateSourceGroup, SWT.PUSH);
browseButton.setText("Browse...");
Listener fileTemplateSelectionListener = new Listener() {
@Override
public void handleEvent(Event event) {
if ( (Boolean) useTemplateFile.getValue() ) {
FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
String result = dialog.open();
if ( result != null ) {
fileTemplateText.setText(result);
}
}
}
};
browseButton.addListener(SWT.Selection, fileTemplateSelectionListener);
fileTemplateText.addListener(SWT.MouseUp, fileTemplateSelectionListener);
bindingContext.bindValue(SWTObservables.observeSelection(fileTemplateOption), useTemplateFile)
.updateTargetToModel();
bindingContext.bindValue(SWTObservables.observeText(fileTemplateText, SWT.Modify), templateFile)
.updateTargetToModel();
ChainValidator<String> templateFileValidationStatusProvider = new ChainValidator<>(templateFile,
useTemplateFile, new NotEmptyValidator("Please provide a valid file for your template"));
bindingContext.addValidationStatusProvider(templateFileValidationStatusProvider);
addStatusDecorator(fileTemplateText, templateFileValidationStatusProvider);
}
private void createSNSTopicControl(final Composite comp, int fieldDecorationWidth) {
final Button notifyWithSNSButton = new Button(comp, SWT.CHECK);
notifyWithSNSButton.setText("SNS Topic (Optional):");
final Combo snsTopicCombo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY);
GridDataFactory.fillDefaults().grab(true, false).indent(fieldDecorationWidth, 0).applyTo(snsTopicCombo);
loadTopics(snsTopicCombo);
bindingContext.bindValue(SWTObservables.observeSelection(notifyWithSNSButton), notifyWithSNS)
.updateTargetToModel();
bindingContext.bindValue(SWTObservables.observeSelection(snsTopicCombo), snsTopicArn).updateTargetToModel();
ChainValidator<String> snsTopicValidationStatusProvider = new ChainValidator<>(snsTopicArn,
notifyWithSNS, new NotEmptyValidator("Please select an SNS notification topic"));
bindingContext.addValidationStatusProvider(snsTopicValidationStatusProvider);
addStatusDecorator(snsTopicCombo, snsTopicValidationStatusProvider);
final Button newTopicButton = new Button(comp, SWT.PUSH);
newTopicButton.setText("Create New Topic");
newTopicButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CreateTopicDialog dialog = new CreateTopicDialog();
if ( dialog.open() == 0 ) {
try {
AwsToolkitCore.getClientFactory().getSNSClient()
.createTopic(new CreateTopicRequest().withName(dialog.getTopicName()));
} catch ( Exception ex ) {
CloudFormationPlugin.getDefault().logError("Failed to create new topic", ex);
}
loadTopics(snsTopicCombo);
}
}
});
snsTopicCombo.setEnabled(false);
newTopicButton.setEnabled(false);
notifyWithSNSButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean selection = notifyWithSNSButton.getSelection();
snsTopicCombo.setEnabled(selection);
newTopicButton.setEnabled(selection);
}
});
}
private void createTimeoutControl(final Composite comp) {
new Label(comp, SWT.None).setText("Creation Timeout:");
Combo timeoutCombo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY);
GridDataFactory.fillDefaults().grab(false, false).span(2, 1).applyTo(timeoutCombo);
timeoutCombo.setItems(new String[] { "None", "5 minutes", "10 minutes", "15 minutes", "20 minutes",
"30 minutes", "60 minutes", "90 minutes", });
timeoutCombo.select(0);
UpdateValueStrategy timeoutUpdateStrategy = new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE);
timeoutUpdateStrategy.setConverter(new IConverter() {
@Override
public Object getToType() {
return Integer.class;
}
@Override
public Object getFromType() {
return String.class;
}
@Override
public Object convert(Object fromObject) {
String value = (String) fromObject;
if ( "None".equals(value) ) {
return 0;
} else {
String minutes = value.substring(0, value.indexOf(' '));
return Integer.parseInt(minutes);
}
}
});
bindingContext.bindValue(SWTObservables.observeSelection(timeoutCombo), timeoutMinutes, timeoutUpdateStrategy,
new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER)).updateTargetToModel();
}
private void createRollbackControl(final Composite comp) {
Button rollbackButton = new Button(comp, SWT.CHECK);
rollbackButton.setText("Rollback on Failure");
GridDataFactory.fillDefaults().grab(false, false).span(3, 1).applyTo(rollbackButton);
rollbackButton.setSelection(true);
bindingContext.bindValue(SWTObservables.observeSelection(rollbackButton), rollbackOnFailure)
.updateTargetToModel();
}
private void setUpValidation(final Composite comp) {
// Change listeners to re-validate the template whenever
// the customer changes whether to use a file or a URL
templateUrl.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
if ( ((String) templateUrl.getValue()).length() > 0 ) {
validateTemplateUrl((String) templateUrl.getValue());
}
}
});
useTemplateUrl.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
if ( (Boolean) useTemplateUrl.getValue() && ((String) templateUrl.getValue()).length() > 0 ) {
validateTemplateUrl((String) templateUrl.getValue());
}
}
});
templateFile.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
validateTemplateFile((String) templateFile.getValue());
}
});
useTemplateFile.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
if ( (Boolean) useTemplateFile.getValue() ) {
validateTemplateFile((String) templateFile.getValue());
}
}
});
// Status validator for template validation, which occurs out of band
IValidator templateValidator = new IValidator() {
@Override
public IStatus validate(Object value) {
if ( value == null ) {
return ValidationStatus.error("No template selected");
}
if ( ((String) value).equals(VALID) ) {
return ValidationStatus.ok();
} else if ( ((String) value).equals(VALIDATING) ) {
return ValidationStatus.warning("Validating template...");
} else if ( ((String) value).equals(INVALID) ) {
if ( templateValidationException != null ) {
return ValidationStatus.error("Invalid template: " + templateValidationException.getMessage());
} else {
return ValidationStatus.error("No template selected");
}
}
return ValidationStatus.ok();
}
};
bindingContext.addValidationStatusProvider(new ChainValidator<String>(templateValidated, templateValidator));
// Also hook up this template validator to the two template fields
// conditionally
addStatusDecorator(fileTemplateText, new ChainValidator<String>(templateValidated, useTemplateFile,
templateValidator));
addStatusDecorator(templateURLText, new ChainValidator<String>(templateValidated, useTemplateUrl,
templateValidator));
// Finally provide aggregate status reporting for the entire wizard page
final AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(bindingContext,
AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object value = aggregateValidationStatus.getValue();
if ( value instanceof IStatus == false )
return;
IStatus status = (IStatus) value;
if ( status.isOK() ) {
setErrorMessage(null);
if (wizard.getDataModel().getMode() == Mode.EstimateCost) {
setMessage(ESTIMATE_COST_OK_MESSAGE, Status.OK);
} else {
setMessage(OK_MESSAGE, Status.OK);
}
} else if (status.getSeverity() == Status.WARNING) {
setErrorMessage(null);
setMessage(status.getMessage(), Status.WARNING);
} else if (status.getSeverity() == Status.ERROR) {
setErrorMessage(status.getMessage());
}
setComplete(status.isOK());
}
});
}
/**
* Adds a control status decorator for the control given.
*/
private void addStatusDecorator(final Control control, ValidationStatusProvider validationStatusProvider) {
ControlDecoration decoration = new ControlDecoration(control, SWT.TOP | SWT.LEFT);
decoration.setDescriptionText("Invalid value");
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(
FieldDecorationRegistry.DEC_ERROR);
decoration.setImage(fieldDecoration.getImage());
new DecorationChangeListener(decoration, validationStatusProvider.getValidationStatus());
}
@Override
public boolean isPageComplete() {
return complete;
}
private void setComplete(boolean complete) {
this.complete = complete;
if ( getWizard().getContainer() != null && getWizard().getContainer().getCurrentPage() != null )
getWizard().getContainer().updateButtons();
}
/**
* Loads all SNS topics into the dropdown given
*/
private void loadTopics(final Combo snsTopicCombo) {
snsTopicCombo.setItems(new String[] { "Loading..." });
new Thread() {
@Override
public void run() {
AmazonSNS sns = AwsToolkitCore.getClientFactory().getSNSClient();
ListTopicsResult topicsResult = sns.listTopics();
final List<String> arns = new ArrayList<>();
for ( Topic topic : topicsResult.getTopics() ) {
arns.add(topic.getTopicArn());
}
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if ( !snsTopicCombo.isDisposed() ) {
snsTopicCombo.setItems(arns.toArray(new String[arns.size()]));
}
}
});
}
}.start();
}
/**
* Validates the template file given in a separate thread.
*/
private void validateTemplateFile(String filePath) {
CancelableThread.cancelThread(validateTemplateThread);
templateValidated.setValue(VALIDATING);
try {
String fileContents = FileUtils.readFileToString(new File(filePath), "UTF8");
validateTemplateThread = new ValidateTemplateThread(
new ValidateTemplateRequest().withTemplateBody(fileContents));
validateTemplateThread.start();
} catch ( Exception e ) {
templateValidated.setValue(INVALID);
templateValidationException = e;
}
}
/**
* Validates the template url given in a separate thread.
*/
private void validateTemplateUrl(String url) {
CancelableThread.cancelThread(validateTemplateThread);
templateValidated.setValue(VALIDATING);
validateTemplateThread = new ValidateTemplateThread(new ValidateTemplateRequest().withTemplateURL(url));
validateTemplateThread.start();
}
/**
* Cancelable thread to validate a template and update the validation
* status.
*/
private final class ValidateTemplateThread extends CancelableThread {
private final ValidateTemplateRequest rq;
private ValidateTemplateThread(ValidateTemplateRequest rq) {
this.rq = rq;
}
@Override
public void run() {
ValidateTemplateResult validateTemplateResult;
Stack existingStack = null;
Map templateMap;
try {
// TODO: region should come from context for file-based actions
AmazonCloudFormation cf = getCloudFormationClient();
validateTemplateResult = cf.validateTemplate(rq);
if ( wizard.getDataModel().getMode() == Mode.Update && wizard.getDataModel().getStackName() != LOADING_STACKS ) {
DescribeStacksResult describeStacks = cf.describeStacks(new DescribeStacksRequest()
.withStackName(wizard.getDataModel().getStackName()));
if ( describeStacks.getStacks().size() == 1 ) {
existingStack = describeStacks.getStacks().iterator().next();
}
}
String templateBody = null;
if ( rq.getTemplateBody() != null ) {
templateBody = rq.getTemplateBody();
} else {
InputStream in = new URL(rq.getTemplateURL()).openStream();
try {
templateBody = IOUtils.toString(in);
} finally {
IOUtils.closeQuietly(in);
}
}
templateMap = parseTemplate(templateBody);
wizard.getDataModel().setTemplateBody(templateBody);
} catch ( Exception e ) {
templateValidationException = e;
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
synchronized ( this ) {
if ( !isCanceled() ) {
templateValidated.setValue(INVALID);
}
}
}
});
setRunning(false);
return;
}
final List<TemplateParameter> templateParams = validateTemplateResult.getParameters();
final Map templateJson = templateMap;
final List<String> requiredCapabilities = validateTemplateResult.getCapabilities();
final Stack stack = existingStack;
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
try {
synchronized ( this ) {
if ( !isCanceled() ) {
wizard.getDataModel().getParametersDataModel().setTemplateParameters(templateParams);
wizard.setNeedsSecondPage(!templateParams.isEmpty());
wizard.getDataModel().getParametersDataModel().setTemplate(templateJson);
wizard.getDataModel().setRequiredCapabilities(requiredCapabilities);
if ( stack != null ) {
for ( Parameter param : stack.getParameters() ) {
boolean noEcho = false;
// This is a pain, but any "noEcho" parameters get returned as asterisks in the service response.
// The customer must fill these values out again, even for a running stack.
for ( TemplateParameter templateParam : wizard.getDataModel().getParametersDataModel().getTemplateParameters() ) {
if (templateParam.getNoEcho() && templateParam.getParameterKey().equals(param.getParameterKey())) {
noEcho = true;
break;
}
}
if ( !noEcho ) {
wizard.getDataModel().getParametersDataModel().getParameterValues()
.put(param.getParameterKey(), param.getParameterValue());
}
}
}
templateValidated.setValue(VALID);
}
}
} finally {
setRunning(false);
}
}
});
}
}
/**
* Parses the (already validated) template given and returns a map of its
* structure.
*/
private Map parseTemplate(String templateBody) throws JsonParseException, IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(templateBody, Map.class);
}
/**
* @return
*/
private AmazonCloudFormation getCloudFormationClient() {
AmazonCloudFormation cf = AwsToolkitCore.getClientFactory().getCloudFormationClient();
return cf;
}
/**
* Whether we can flip to the next page depends on whether there's one to go to.
*/
@Override
public boolean canFlipToNextPage() {
return (wizard.needsSecondPage() || wizard.needsThirdPage()) && super.canFlipToNextPage();
}
} | 8,056 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/explorer/cloudformation/wizard/CreateStackWizardThirdPage.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.cloudformation.wizard;
import static com.amazonaws.eclipse.cloudformation.CloudFormationConstants.MAX_ALLOWED_TAG_AMOUNT;
import static com.amazonaws.eclipse.cloudformation.CloudFormationConstants.MAX_TAG_KEY_LENGTH;
import static com.amazonaws.eclipse.cloudformation.CloudFormationConstants.MAX_TAG_VALUE_LENGTH;
import java.util.List;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import com.amazonaws.eclipse.cloudformation.CloudFormationUtils;
import com.amazonaws.eclipse.core.model.KeyValueSetDataModel.Pair;
import com.amazonaws.eclipse.core.ui.KeyValueSetEditingComposite;
import com.amazonaws.eclipse.core.ui.KeyValueSetEditingComposite.KeyValueSetEditingCompositeBuilder;
import com.amazonaws.eclipse.core.validator.StringLengthValidator;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizardDataModel.Mode;
import com.amazonaws.services.cloudformation.model.Tag;
/**
* Configuring stack tags page in create CloudFormation stack wizard.
*/
public class CreateStackWizardThirdPage extends WizardPage {
private final CreateStackWizardDataModel dataModel;
private KeyValueSetEditingComposite tagsEditingComposite;
protected CreateStackWizardThirdPage(CreateStackWizardDataModel dataModel) {
super("CloudFormation Stack Tags");
setTitle("Options - Tags");
setDescription(String.format("You can specify tags (key-value pairs) for resources in your stack. You can add up to %d unique key-value pairs for each stack.",
MAX_ALLOWED_TAG_AMOUNT ));
this.dataModel = dataModel;
if (dataModel.getMode() == Mode.Update) {
List<Tag> tags = CloudFormationUtils.getTags(dataModel.getStackName());
if (tags != null && !tags.isEmpty()) {
for (Tag tag : tags) {
dataModel.getTagModel().getPairSet().add(new Pair(tag.getKey(), tag.getValue()));
}
}
}
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
createTagSection(composite);
setControl(composite);
}
private void createTagSection(Composite parent) {
tagsEditingComposite = new KeyValueSetEditingCompositeBuilder()
.addKeyValidator(new StringLengthValidator(1, MAX_TAG_KEY_LENGTH,
String.format("The tag key length must be between %d and %d, inclusive.", 1, MAX_TAG_KEY_LENGTH)))
.addValueValidator(new StringLengthValidator(1, MAX_TAG_VALUE_LENGTH,
String.format("The tag value length must be between %d and %d, inclusive", 1, MAX_TAG_VALUE_LENGTH)))
.build(parent, dataModel.getTagModel());
}
@Override
public boolean canFlipToNextPage() {
return false;
}
}
| 8,057 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/CloudFormationPlugin.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation;
import org.osgi.framework.BundleContext;
import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin;
/**
* The activator class controls the plug-in life cycle
*/
public class CloudFormationPlugin extends AbstractAwsPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "com.amazonaws.eclipse.cloudformation"; //$NON-NLS-1$
// The shared instance
private static CloudFormationPlugin plugin;
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static CloudFormationPlugin getDefault() {
return plugin;
}
}
| 8,058 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/CloudFormationConstants.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation;
/**
* Constants in CloudFormation service.
*/
public class CloudFormationConstants {
public static final int MAX_TAG_KEY_LENGTH = 127;
public static final int MAX_TAG_VALUE_LENGTH = 255;
public static final int MAX_ALLOWED_TAG_AMOUNT = 50;
}
| 8,059 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/CloudFormationUtils.java | /*
* Copyright 2016 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.model.DescribeStacksRequest;
import com.amazonaws.services.cloudformation.model.ListStacksRequest;
import com.amazonaws.services.cloudformation.model.ListStacksResult;
import com.amazonaws.services.cloudformation.model.StackStatus;
import com.amazonaws.services.cloudformation.model.StackSummary;
import com.amazonaws.services.cloudformation.model.Tag;
public class CloudFormationUtils {
/**
* Iterate all the existing stacks and return the preferred list of elements which could be converted from StackSummary.
*/
public static <T> List<T> listExistingStacks(StackSummaryConverter<T> converter) {
return listExistingStacks(RegionUtils.getCurrentRegion().getId(), converter);
}
public static List<StackSummary> listExistingStacks(String regionId) {
return listExistingStacks(regionId, new StackSummaryConverter<StackSummary>() {
@Override
public StackSummary convert(StackSummary stack) {
return stack;
}
});
}
private static <T> List<T> listExistingStacks(String regionId, StackSummaryConverter<T> converter) {
AmazonCloudFormation cloudFormation = AwsToolkitCore.getClientFactory().getCloudFormationClientByRegion(regionId);
List<T> newItems = new ArrayList<>();
ListStacksRequest request = new ListStacksRequest();
ListStacksResult result = null;
do {
result = cloudFormation.listStacks(request);
for (StackSummary stack : result.getStackSummaries()) {
if (stack.getStackStatus().equalsIgnoreCase(StackStatus.DELETE_COMPLETE.toString())) continue;
if (stack.getStackStatus().equalsIgnoreCase(StackStatus.DELETE_IN_PROGRESS.toString())) continue;
newItems.add(converter.convert(stack));
}
request.setNextToken(result.getNextToken());
} while (result.getNextToken() != null);
return newItems;
}
public interface StackSummaryConverter<T> {
T convert(StackSummary stack);
}
public static List<Tag> getTags(String stackName) {
AmazonCloudFormation cloudFormation = AwsToolkitCore.getClientFactory().getCloudFormationClient();
try {
return cloudFormation.describeStacks(new DescribeStacksRequest().withStackName(stackName)).getStacks().get(0).getTags();
} catch (Exception e) {
CloudFormationPlugin.getDefault().logError(e.getMessage(), e);
return Collections.emptyList();
}
}
}
| 8,060 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/ui/ParametersComposite.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.cloudformation.ui;
import static com.amazonaws.eclipse.cloudformation.validators.TemplateParameterValidators.newMaxLengthValidator;
import static com.amazonaws.eclipse.cloudformation.validators.TemplateParameterValidators.newMaxValueValidator;
import static com.amazonaws.eclipse.cloudformation.validators.TemplateParameterValidators.newMinLengthValidator;
import static com.amazonaws.eclipse.cloudformation.validators.TemplateParameterValidators.newMinValueValidator;
import static com.amazonaws.eclipse.cloudformation.validators.TemplateParameterValidators.newPatternValidator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.Observables;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.cloudformation.model.ParametersDataModel;
import com.amazonaws.eclipse.databinding.ChainValidator;
import com.amazonaws.eclipse.databinding.DecorationChangeListener;
import com.amazonaws.services.cloudformation.model.TemplateParameter;
/**
* A composite dynamically built from a set of AWS CloudFormation template parameters.
*/
public class ParametersComposite extends Composite {
private static final String ALLOWED_VALUES = "AllowedValues";
private static final String MAX_LENGTH = "MaxLength";
private static final String MIN_LENGTH = "MinLength";
private static final String MAX_VALUE = "MaxValue";
private static final String MIN_VALUE = "MinValue";
private static final String CONSTRAINT_DESCRIPTION = "ConstraintDescription";
private static final String ALLOWED_PATTERN = "AllowedPattern";
private final ParametersDataModel dataModel;
private final DataBindingContext bindingContext;
private final Map<?, ?> parameterMap;
public ParametersComposite(Composite parent, ParametersDataModel dataModel, DataBindingContext bindingContext) {
super(parent, SWT.NONE);
this.dataModel = dataModel;
this.parameterMap = (Map<?, ?>) dataModel.getTemplate().get("Parameters");
this.bindingContext = bindingContext;
setLayout(new GridLayout(2, false));
setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
createControls();
}
private void createControls() {
if (dataModel.getTemplateParameters() == null || dataModel.getTemplateParameters().isEmpty()) {
Label label = new Label(this, SWT.NONE);
label.setText("Selected template has no parameters");
label.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false, 2, 1));
}
for (TemplateParameter param : dataModel.getTemplateParameters()) {
createParameterSection(param);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void createParameterSection(TemplateParameter param) {
// Unfortunately, we have to manually adjust for field decorations
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(
FieldDecorationRegistry.DEC_ERROR);
int fieldDecorationWidth = fieldDecoration.getImage().getBounds().width;
Control paramControl = null;
ISWTObservableValue observeParameter = null;
ChainValidator<String> validationStatusProvider = null;
if ( parameterMap.containsKey(param.getParameterKey()) ) {
Label label = new Label(this, SWT.None);
label.setText(param.getParameterKey());
Map paramMap = (Map) parameterMap.get(param.getParameterKey());
// Update the default value in the model.
if (dataModel.getParameterValues().get(param.getParameterKey()) == null) {
dataModel.getParameterValues().put(param.getParameterKey(), param.getDefaultValue());
}
// If the template enumerates allowed values, present them as a
// combo drop down
if ( paramMap.containsKey(ALLOWED_VALUES) ) {
Combo combo = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
Collection<String> allowedValues = (Collection<String>) paramMap.get(ALLOWED_VALUES);
GridDataFactory.fillDefaults().grab(true, false).indent(fieldDecorationWidth, 0).applyTo(combo);
combo.setItems(allowedValues.toArray(new String[allowedValues.size()]));
observeParameter = SWTObservables.observeSelection(combo);
paramControl = combo;
} else {
// Otherwise, just use a text field with validation constraints
Text text = new Text(this, SWT.BORDER);
GridDataFactory.fillDefaults().grab(true, false).indent(fieldDecorationWidth, 0).applyTo(text);
observeParameter = SWTObservables.observeText(text, SWT.Modify);
paramControl = text;
// Add validators for the constraints listed in the template
List<IValidator> validators = new ArrayList<>();
if ( paramMap.containsKey(ALLOWED_PATTERN) ) {
String pattern = (String) paramMap.get(ALLOWED_PATTERN);
Pattern p = Pattern.compile(pattern);
validators.add(newPatternValidator(p, param.getParameterKey() + ": "
+ (String) paramMap.get(CONSTRAINT_DESCRIPTION)));
}
if ( paramMap.containsKey(MIN_LENGTH) ) {
validators.add(newMinLengthValidator(parseValueToInteger(paramMap.get(MIN_LENGTH)), param
.getParameterKey()));
}
if ( paramMap.containsKey(MAX_LENGTH) ) {
validators.add(newMaxLengthValidator(parseValueToInteger(paramMap.get(MAX_LENGTH)), param
.getParameterKey()));
}
if ( paramMap.containsKey(MIN_VALUE) ) {
validators.add(newMinValueValidator(parseValueToInteger(paramMap.get(MIN_VALUE)), param
.getParameterKey()));
}
if ( paramMap.containsKey(MAX_VALUE) ) {
validators.add(newMaxValueValidator(parseValueToInteger(paramMap.get(MAX_VALUE)), param
.getParameterKey()));
}
if ( !validators.isEmpty() ) {
validationStatusProvider = new ChainValidator<>(observeParameter,
validators.toArray(new IValidator[validators.size()]));
}
}
} else {
CloudFormationPlugin.getDefault().logError("No parameter map object found for " + param.getParameterKey(),
null);
return;
}
if (param.getDescription() != null) {
Label description = new Label(this, SWT.WRAP);
GridDataFactory.fillDefaults().grab(true, false).span(2, 1).indent(0, -8).applyTo(description);
description.setText(param.getDescription());
description.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY));
}
bindingContext.bindValue(observeParameter, Observables.observeMapEntry(
dataModel.getParameterValues(), param.getParameterKey(), String.class));
if ( validationStatusProvider != null ) {
bindingContext.addValidationStatusProvider(validationStatusProvider);
ControlDecoration decoration = new ControlDecoration(paramControl, SWT.TOP | SWT.LEFT);
decoration.setDescriptionText("Invalid value");
decoration.setImage(fieldDecoration.getImage());
new DecorationChangeListener(decoration, validationStatusProvider.getValidationStatus());
}
}
private int parseValueToInteger(Object value) {
if (value instanceof Integer) {
return ((Integer) value).intValue();
} else {
return Integer.parseInt((String) value);
}
}
}
| 8,061 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/preferences/PreferenceInitializer.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.preferences;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
public class PreferenceInitializer extends AbstractPreferenceInitializer {
@Override
public void initializeDefaultPreferences() {
EditorPreferences defaultEditorPreferences = EditorPreferences.getDefaultPreferences();
IPreferenceStore store = CloudFormationPlugin.getDefault().getPreferenceStore();
EditorPreferencesLoader.loadDefaultPreferences(store, defaultEditorPreferences);
}
}
| 8,062 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/preferences/EditorPreferences.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.preferences;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.TextAttribute;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class EditorPreferences {
private static EditorPreferences DEFAULT_EDITOR_PREFERENCES;
private Map<String, TokenPreference> highlight;
public static EditorPreferences getDefaultPreferences() {
if (DEFAULT_EDITOR_PREFERENCES == null) {
try {
InputStream inputStream = EditorPreferences.class
.getResourceAsStream("template-default-preferences.json");
DEFAULT_EDITOR_PREFERENCES = new ObjectMapper().readValue(inputStream, EditorPreferences.class);
} catch (IOException e) {
CloudFormationPlugin.getDefault().logError(e.getMessage(), e);
}
}
return DEFAULT_EDITOR_PREFERENCES;
}
public static Map<String, TokenPreference> buildHighlightPreferences(IPreferenceStore store) {
Map<String, TokenPreference> highlightPreferences = new HashMap<>();
for (TemplateTokenPreferenceNames names : TemplateTokenPreferenceNames.values()) {
TokenPreference tokenPreference = TokenPreference.buildTemplateToken(store, names);
highlightPreferences.put(tokenPreference.getId(), tokenPreference);
}
return highlightPreferences;
}
public Map<String, TokenPreference> getHighlight() {
return highlight;
}
public void setHighlight(Map<String, TokenPreference> highlight) {
this.highlight = highlight;
}
public static class TokenPreference {
private final String id;
@JsonIgnore
private final TemplateTokenPreferenceNames preferenceNames;
private Color color;
private Boolean bold;
private Boolean italic;
@JsonCreator
public TokenPreference(
@JsonProperty("id") String id,
@JsonProperty("color") Color color,
@JsonProperty("bold") Boolean bold,
@JsonProperty("italic") Boolean italic) {
this.id = id;
this.color = color;
this.bold = bold;
this.italic = italic;
this.preferenceNames = TemplateTokenPreferenceNames.fromValue(id);
}
public TextAttribute toTextAttribute() {
RGB rgb = new RGB(getColor().getRed(), getColor().getGreen(), getColor().getBlue());
int style = 0x00;
if (bold) {
style |= SWT.BOLD;
}
if (italic) {
style |= SWT.ITALIC;
}
return new TextAttribute(new org.eclipse.swt.graphics.Color(Display.getCurrent(), rgb), null, style);
}
public String getId() {
return id;
}
@JsonIgnore
public String getDisplayLabel() {
return preferenceNames.getDisplayLabel();
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
@JsonIgnore
public String getColorRedPropertyName() {
return preferenceNames.getColorRed();
}
@JsonIgnore
public String getColorGreenPropertyName() {
return preferenceNames.getColorGreen();
}
@JsonIgnore
public String getColorBluePropertyName() {
return preferenceNames.getColorBlue();
}
public Boolean getBold() {
return bold;
}
public void setBold(Boolean bold) {
this.bold = bold;
}
@JsonIgnore
public String getBoldPropertyName() {
return preferenceNames.getBold();
}
public Boolean getItalic() {
return italic;
}
public void setItalic(Boolean italic) {
this.italic = italic;
}
@JsonIgnore
public String getItalicPropertyName() {
return preferenceNames.getItalic();
}
/**
* Build a template token from the given preference store according to the preference names of the token.
*/
public static TokenPreference buildTemplateToken(IPreferenceStore store, TemplateTokenPreferenceNames preferenceNames) {
Color color = new Color(
store.getInt(preferenceNames.getColorRed()),
store.getInt(preferenceNames.getColorGreen()),
store.getInt(preferenceNames.getColorBlue())
);
Boolean bold = store.getBoolean(preferenceNames.getBold());
Boolean italic = store.getBoolean(preferenceNames.getItalic());
return new TokenPreference(preferenceNames.getId(), color, bold, italic);
}
}
public static class Color {
private int red;
private int green;
private int blue;
@JsonCreator
public Color(
@JsonProperty("red") int red,
@JsonProperty("green") int green,
@JsonProperty("blue") int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public int getRed() {
return red;
}
public void setRed(int red) {
this.red = red;
}
public int getGreen() {
return green;
}
public void setGreen(int green) {
this.green = green;
}
public int getBlue() {
return blue;
}
public void setBlue(int blue) {
this.blue = blue;
}
}
}
| 8,063 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/preferences/EditorPreferencesLoader.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.preferences;
import org.eclipse.jface.preference.IPreferenceStore;
import com.amazonaws.eclipse.cloudformation.preferences.EditorPreferences.TokenPreference;
public class EditorPreferencesLoader {
/**
* Load default editor preferences to the specified preference store.
*/
static void loadDefaultPreferences(IPreferenceStore store, EditorPreferences preferences) {
for (TokenPreference tokenPreference : preferences.getHighlight().values()) {
loadDefaultTokenPreferences(store, tokenPreference);
}
}
private static void loadDefaultTokenPreferences(IPreferenceStore store, TokenPreference tokenPreference) {
store.setDefault(tokenPreference.getColorRedPropertyName(), tokenPreference.getColor().getRed());
store.setDefault(tokenPreference.getColorGreenPropertyName(), tokenPreference.getColor().getGreen());
store.setDefault(tokenPreference.getColorBluePropertyName(), tokenPreference.getColor().getBlue());
store.setDefault(tokenPreference.getBoldPropertyName(), tokenPreference.getBold());
store.setDefault(tokenPreference.getItalicPropertyName(), tokenPreference.getItalic());
}
/**
* Load editor preferences to the specified preference store.
* @see {@link TokenPreference#buildTemplateToken(IPreferenceStore, TemplateTokenPreferenceNames)}
*/
public static void loadPreferences(IPreferenceStore store, EditorPreferences preferences) {
for (TokenPreference tokenPreference : preferences.getHighlight().values()) {
loadTokenPreferences(store, tokenPreference);
}
}
public static void loadTokenPreferences(IPreferenceStore store, TokenPreference tokenPreference) {
store.setValue(tokenPreference.getColorRedPropertyName(), tokenPreference.getColor().getRed());
store.setValue(tokenPreference.getColorGreenPropertyName(), tokenPreference.getColor().getGreen());
store.setValue(tokenPreference.getColorBluePropertyName(), tokenPreference.getColor().getBlue());
store.setValue(tokenPreference.getBoldPropertyName(), tokenPreference.getBold());
store.setValue(tokenPreference.getItalicPropertyName(), tokenPreference.getItalic());
}
private static void loadTokenPreferences(IPreferenceStore from, TemplateTokenPreferenceNames tokenPreferenceNames, IPreferenceStore to) {
to.setValue(tokenPreferenceNames.getColorRed(), from.getInt(tokenPreferenceNames.getColorRed()));
to.setValue(tokenPreferenceNames.getColorGreen(), from.getInt(tokenPreferenceNames.getColorGreen()));
to.setValue(tokenPreferenceNames.getColorBlue(), from.getInt(tokenPreferenceNames.getColorBlue()));
to.setValue(tokenPreferenceNames.getBold(), from.getBoolean(tokenPreferenceNames.getBold()));
to.setValue(tokenPreferenceNames.getItalic(), from.getBoolean(tokenPreferenceNames.getItalic()));
}
public static void loadPreferences(IPreferenceStore from, IPreferenceStore to) {
for (TemplateTokenPreferenceNames names : TemplateTokenPreferenceNames.values()) {
loadTokenPreferences(from, names, to);
}
}
} | 8,064 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/preferences/TemplateTokenPreferenceNames.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.preferences;
/**
* The preference names for the given template token.
*/
public enum TemplateTokenPreferenceNames {
/* The id value for these tokens must be identical to the default preferences configuration file*/
KEY("keyToken", "Key Token"),
VALUE("valueToken", "Value Token"),
INTRINSIC_FUNCTION("intrinsicFunctionToken", "Intrinsic Function Name"),
PSEUDO_PARAMETER("pseudoParameterToken", "Pseudo Parameter"),
RESOURCE_TYPE("resourceTypeToken", "AWS Resource Type"),
;
// Preference name prefix
private static final String PREFIX = "com.amazonaws.cloudformation.editor";
private final String id;
private final String displayLabel;
private final String colorRed;
private final String colorGreen;
private final String colorBlue;
private final String bold;
private final String italic;
private TemplateTokenPreferenceNames(String id, String displayLabel) {
this.id = id;
this.displayLabel = displayLabel;
this.colorRed = PREFIX + "." + id + ".red";
this.colorGreen = PREFIX + "." + id + ".green";
this.colorBlue = PREFIX + "." + id + ".blue";
this.bold = PREFIX + "." + id + ".bold";
this.italic = PREFIX + "." + id + ".italic";
}
public String getId() {
return id;
}
public String getDisplayLabel() {
return displayLabel;
}
public String getColorRed() {
return colorRed;
}
public String getColorGreen() {
return colorGreen;
}
public String getColorBlue() {
return colorBlue;
}
public String getBold() {
return bold;
}
public String getItalic() {
return italic;
}
public static boolean isCloudFormationEditorProperty(String propertyName) {
return propertyName.startsWith(PREFIX);
}
public static TemplateTokenPreferenceNames fromValue(String id) {
for (TemplateTokenPreferenceNames names : TemplateTokenPreferenceNames.values()) {
if (names.getId().equalsIgnoreCase(id)) {
return names;
}
}
assert(false);
return null;
}
}
| 8,065 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/preferences/SyntaxColoringPreferencePage.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.preferences;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCheckbox;
import java.io.IOException;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer;
import org.eclipse.jface.preference.ColorSelector;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.RGB;
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.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.cloudformation.preferences.EditorPreferences.Color;
import com.amazonaws.eclipse.cloudformation.preferences.EditorPreferences.TokenPreference;
import com.amazonaws.eclipse.cloudformation.templates.editor.TemplateDocument;
import com.amazonaws.eclipse.cloudformation.templates.editor.TemplateSourceViewerConfiguration;
import com.amazonaws.eclipse.core.ui.preferences.AwsToolkitPreferencePage;
import com.amazonaws.util.IOUtils;
/**
* Preference page for setting CloudFormation template editor highlighting.
*/
public class SyntaxColoringPreferencePage extends AwsToolkitPreferencePage implements IWorkbenchPreferencePage {
private static final String GLOBAL_FONT_PROPERTY_NAME = "org.eclipse.jdt.ui.editors.textfont";
private final EditorPreferences model = new EditorPreferences();
// PreferenceStore to be used for the preview viewer.
private final IPreferenceStore overlayPreferenceStore = new PreferenceStore();
// UIs in this preference page
private List tokenList;
private ColorSelector colorSelector;
private Button isBoldButton;
private Button isItalicButton;
private JavaSourceViewer fPreviewViewer;
public SyntaxColoringPreferencePage() {
super("CloudFormation Template Syntax Coloring Preference Page");
}
@Override
public void init(IWorkbench workbench) {
setPreferenceStore(CloudFormationPlugin.getDefault().getPreferenceStore());
initModel();
initOverlayPreferenceStore();
}
@Override
protected Control createContents(Composite parent) {
final Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
createTokenSelectionSection(composite);
createStyleSelectionSection(composite);
createPreviewer(composite);
onTokenListSelected();
return composite;
}
@Override
protected void performDefaults() {
EditorPreferences defaultPreferences = EditorPreferences.getDefaultPreferences();
hardCopyToModel(defaultPreferences);
onTokenListSelected();
EditorPreferencesLoader.loadPreferences(overlayPreferenceStore, model);
super.performDefaults();
}
@Override
public void performApply() {
onPerformApply();
super.performApply();
}
@Override
public boolean performOk() {
onPerformApply();
return super.performOk();
}
private void createTokenSelectionSection(Composite composite) {
Composite tokenComposite = new Composite(composite, SWT.NONE);
tokenComposite.setLayout(new GridLayout());
tokenComposite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
new Label(tokenComposite, SWT.NONE).setText("Element:");
tokenList = new List(tokenComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
for (TokenPreference tokenPreference : model.getHighlight().values()) {
tokenList.add(tokenPreference.getDisplayLabel());
tokenList.setData(tokenPreference.getDisplayLabel(), tokenPreference);
}
tokenList.select(0);
tokenList.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onTokenListSelected();
}
});
}
private void createStyleSelectionSection(Composite composite) {
Composite styleComposite = new Composite(composite, SWT.NONE);
styleComposite.setLayout(new GridLayout(2, false));
styleComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
newLabel("Color: ", styleComposite);
colorSelector = new ColorSelector(styleComposite);
isBoldButton = newCheckbox(styleComposite, "Bold", 2);
isItalicButton = newCheckbox(styleComposite, "Italic", 2);
colorSelector.addListener(new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
onColorSelectorChanged();
}
});
isBoldButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onIsBoldButtonSelected();
}
});
isItalicButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onIsItalicButtonSelected();
}
});
}
@SuppressWarnings("restriction")
private void createPreviewer(Composite parent) {
GridData data = new GridData();
data.horizontalSpan = 2;
newLabel("Preview:", parent).setLayoutData(data);
IPreferenceStore store= new ChainedPreferenceStore(new IPreferenceStore[] { overlayPreferenceStore, JavaPlugin.getDefault().getCombinedPreferenceStore()});
fPreviewViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store);
TemplateSourceViewerConfiguration configuration = new TemplateSourceViewerConfiguration(store);
fPreviewViewer.configure(configuration);
Font font= JFaceResources.getFont(GLOBAL_FONT_PROPERTY_NAME);
fPreviewViewer.getTextWidget().setFont(font);
new SourcePreviewerUpdater(fPreviewViewer, configuration, store);
fPreviewViewer.setEditable(false);
data = new GridData(GridData.FILL_BOTH);
data.horizontalSpan = 2;
fPreviewViewer.getControl().setLayoutData(data);
String content= loadPreviewContentFromFile();
TemplateDocument document = new TemplateDocument();
document.set(content);
fPreviewViewer.setDocument(document);
}
private void initModel() {
IPreferenceStore store = getPreferenceStore();
model.setHighlight(EditorPreferences.buildHighlightPreferences(store));
}
private void initOverlayPreferenceStore() {
IPreferenceStore store = getPreferenceStore();
EditorPreferencesLoader.loadPreferences(store, overlayPreferenceStore);
}
private TokenPreference getSelectedToken() {
String key = tokenList.getItems()[tokenList.getSelectionIndex()];
return (TokenPreference) tokenList.getData(key);
}
private void onTokenListSelected() {
TokenPreference tokenPreference = getSelectedToken();
colorSelector.setColorValue(new RGB(
tokenPreference.getColor().getRed(),
tokenPreference.getColor().getGreen(),
tokenPreference.getColor().getBlue()));
isBoldButton.setSelection(tokenPreference.getBold());
isItalicButton.setSelection(tokenPreference.getItalic());
}
private void onColorSelectorChanged() {
RGB rgb = colorSelector.getColorValue();
TokenPreference token = getSelectedToken();
Color color = new Color(rgb.red, rgb.green, rgb.blue);
token.setColor(color);
EditorPreferencesLoader.loadTokenPreferences(overlayPreferenceStore, token);
}
private void onIsBoldButtonSelected() {
TokenPreference token = getSelectedToken();
token.setBold(isBoldButton.getSelection());
EditorPreferencesLoader.loadTokenPreferences(overlayPreferenceStore, token);
}
private void onIsItalicButtonSelected() {
TokenPreference token = getSelectedToken();
token.setItalic(isItalicButton.getSelection());
EditorPreferencesLoader.loadTokenPreferences(overlayPreferenceStore, token);
}
private void onPerformApply() {
EditorPreferencesLoader.loadPreferences(getPreferenceStore(), model);
}
private void hardCopyToModel(EditorPreferences from) {
for (TokenPreference tokenPreference : from.getHighlight().values()) {
hardCopy(from.getHighlight().get(tokenPreference.getId()),
model.getHighlight().get(tokenPreference.getId()));
}
}
private static void hardCopy(TokenPreference from, TokenPreference to) {
to.setBold(from.getBold());
to.setItalic(from.getItalic());
to.setColor(new Color(
from.getColor().getRed(), from.getColor().getGreen(), from.getColor().getBlue()));
}
private static class SourcePreviewerUpdater {
/**
* Creates a Java source preview updater for the given viewer, configuration and preference store.
*
* @param viewer the viewer
* @param configuration the configuration
* @param preferenceStore the preference store
*/
SourcePreviewerUpdater(final SourceViewer viewer, final TemplateSourceViewerConfiguration configuration, final IPreferenceStore preferenceStore) {
Assert.isNotNull(viewer);
Assert.isNotNull(configuration);
Assert.isNotNull(preferenceStore);
final IPropertyChangeListener fontChangeListener= new IPropertyChangeListener() {
/*
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(GLOBAL_FONT_PROPERTY_NAME)) {
Font font= JFaceResources.getFont(GLOBAL_FONT_PROPERTY_NAME);
viewer.getTextWidget().setFont(font);
}
}
};
final IPropertyChangeListener propertyChangeListener= new IPropertyChangeListener() {
/*
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (TemplateTokenPreferenceNames.isCloudFormationEditorProperty(event.getProperty())) {
configuration.handlePropertyChange(event);
viewer.invalidateTextPresentation();
}
}
};
viewer.getTextWidget().addDisposeListener(new DisposeListener() {
/*
* @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent)
*/
public void widgetDisposed(DisposeEvent e) {
preferenceStore.removePropertyChangeListener(propertyChangeListener);
JFaceResources.getFontRegistry().removeListener(fontChangeListener);
}
});
JFaceResources.getFontRegistry().addListener(fontChangeListener);
preferenceStore.addPropertyChangeListener(propertyChangeListener);
}
}
private String loadPreviewContentFromFile() {
String previewDocumentFile = "preview-document-content.json";
String content =
"{\n" +
" \"AWSTemplateFormatVersion\" : \"2010-09-09\",\n" +
" \"Resources\" : {\n" +
" \"S3Bucket\": {\n" +
" \"Type\" : \"AWS::S3::Bucket\",\n" +
" \"Properties\" : {\n" +
" \"BucketName\" : \"bucketname\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
try {
return IOUtils.toString(SyntaxColoringPreferencePage.class.getResourceAsStream(previewDocumentFile));
} catch (IOException e) {
return content;
}
}
}
| 8,066 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/preferences/PreferencePage.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.core.ui.preferences.AwsToolkitPreferencePage;
public class PreferencePage extends AwsToolkitPreferencePage implements IWorkbenchPreferencePage {
public PreferencePage() {
super("CloudFormation Template Preferences");
}
@Override
public void init(IWorkbench workbench) {
setPreferenceStore(CloudFormationPlugin.getDefault().getPreferenceStore());
}
@Override
protected Control createContents(Composite parent) {
final Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
newLabel("Expand the tree to edit preferences for CloudFormation Template Editor.", composite);
return composite;
}
}
| 8,067 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/model/ParametersDataModel.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.cloudformation.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.databinding.observable.map.WritableMap;
import com.amazonaws.eclipse.cloudformation.ui.ParametersComposite;
import com.amazonaws.services.cloudformation.model.Parameter;
import com.amazonaws.services.cloudformation.model.TemplateParameter;
/**
* Data model for {@link ParametersComposite}.
*/
public class ParametersDataModel {
// This is from {@link ValidateTemplateResult}, which are parameters in the local template file.
private List<TemplateParameter> templateParameters;
// This is from {@link Stack}, which are parameters from the existing Stack.
private final List<Parameter> parameters = new ArrayList<>();
// This is a list of parameters collected from the Wizard UI.
private final WritableMap parameterValues = new WritableMap(String.class, String.class);
private Map template;
public List<TemplateParameter> getTemplateParameters() {
return templateParameters;
}
public void setTemplateParameters(List<TemplateParameter> templateParameters) {
this.templateParameters = templateParameters;
}
public WritableMap getParameterValues() {
return parameterValues;
}
public Map getTemplate() {
return template;
}
public void setTemplate(Map template) {
this.template = template;
}
public List<Parameter> getParameters() {
return parameters;
}
}
| 8,068 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/actions/TemplateEditorBaseAction.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.actions;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.FileEditorInput;
import com.amazonaws.eclipse.cloudformation.templates.editor.TemplateDocument;
import com.amazonaws.eclipse.cloudformation.templates.editor.TemplateEditor;
/**
* Base class for context sensitive actions in the TemplateEditor
*/
abstract class TemplateEditorBaseAction implements IObjectActionDelegate {
protected IPath filePath;
protected TemplateDocument templateDocument;
@Override
public void selectionChanged(IAction action, ISelection selection) {}
@Override
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
if ( targetPart instanceof TemplateEditor ) {
TemplateEditor templateEditor = (TemplateEditor)targetPart;
templateDocument = templateEditor.getTemplateDocument();
IEditorInput editorInput = templateEditor.getEditorInput();
if ( editorInput instanceof FileEditorInput ) {
filePath = ((FileEditorInput) editorInput).getPath();
}
}
}
} | 8,069 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/actions/UpdateStackAction.java | package com.amazonaws.eclipse.cloudformation.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizard;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizardDataModel.Mode;
public class UpdateStackAction extends TemplateEditorBaseAction {
/* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
@Override
public void run(IAction action) {
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new CreateStackWizard(filePath, Mode.Update));
dialog.open();
}
}
| 8,070 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/actions/CreateStackAction.java | package com.amazonaws.eclipse.cloudformation.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizard;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizardDataModel.Mode;
public class CreateStackAction extends TemplateEditorBaseAction {
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
@Override
public void run(IAction action) {
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new CreateStackWizard(filePath, Mode.Create));
dialog.open();
}
}
| 8,071 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/actions/EstimateTemplateCostAction.java | /*
* Copyright 2013 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizard;
import com.amazonaws.eclipse.explorer.cloudformation.wizard.CreateStackWizardDataModel.Mode;
public class EstimateTemplateCostAction extends TemplateEditorBaseAction {
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
@Override
public void run(IAction action) {
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new CreateStackWizard(filePath, Mode.EstimateCost));
dialog.open();
}
}
| 8,072 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/actions/FormatTemplateAction.java | /*
* Copyright 2013 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.actions;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IAction;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.explorer.cloudformation.JsonFormatter;
/**
* Formats a CloudFormation template document. The document must be valid JSON
* in order for it to be formatted.
*/
public class FormatTemplateAction extends TemplateEditorBaseAction {
@Override
public void run(IAction action) {
try {
String documentText = templateDocument.get(0, templateDocument.getLength());
String formattedText = JsonFormatter.format(documentText);
templateDocument.replace(0, templateDocument.getLength(), formattedText);
} catch (Exception e) {
String message = "Unable to format document. Make sure the document is well-formed JSON before attempting to format.";
IStatus status = new Status(IStatus.ERROR, CloudFormationPlugin.PLUGIN_ID, message);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
}
| 8,073 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/TemplateNodePath.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* A path used to denote the target template node from ROOT.
*/
public class TemplateNodePath {
public static class PathNode {
private static final String PATH_NODE_SEPARATOR = ",";
private final String fieldName;
private final Integer index;
private final List<String> parameters;
public PathNode(Integer index) {
this(null, index);
}
public PathNode(String fieldName, String... parameters) {
this(fieldName, null, parameters);
}
private PathNode(String fieldName, Integer index, String... parameters) {
this.fieldName = fieldName;
this.index = index;
this.parameters = Collections.unmodifiableList(Arrays.asList(parameters));
}
public String getFieldName() {
return fieldName;
}
public Integer getIndex() {
return index;
}
public List<String> getParameters() {
return parameters;
}
public String getReadiblePath() {
if (index != null) {
return String.valueOf(index);
}
StringBuilder builder = new StringBuilder(fieldName);
for (String parameter : parameters) {
builder.append(PATH_NODE_SEPARATOR + parameter);
}
return builder.toString();
}
@Override
public String toString() {
return getReadiblePath();
}
}
}
| 8,074 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/TemplateIndexNode.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates;
public class TemplateIndexNode extends TemplateNode {
private final int index;
public TemplateIndexNode(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
}
| 8,075 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/TemplateValueNode.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates;
/**
* Represents a JSON value in a Template document.
*/
public class TemplateValueNode extends TemplateNode {
private final String text;
public TemplateValueNode(String text) {
this.text = text;
}
public String getText() {
return text;
}
} | 8,076 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/TemplateObjectNode.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.fasterxml.jackson.core.JsonLocation;
/**
* Represents a JSON object structure in a Template document.
*/
public class TemplateObjectNode extends TemplateNode {
private Map<String, TemplateNode> map = new LinkedHashMap<>();
public TemplateObjectNode(JsonLocation startLocation) {
setStartLocation(startLocation);
}
public void put(String field, TemplateNode value) {
TemplateFieldNode fieldNode = new TemplateFieldNode(field);
fieldNode.setParent(this);
value.setParent(fieldNode);
map.put(field, value);
}
public TemplateNode get(String field) {
return map.get(field);
}
public Set<Entry<String,TemplateNode>> getFields() {
return map.entrySet();
}
} | 8,077 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/TemplateArrayNode.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonLocation;
/**
* Represents a JSON array structure in a Template document.
*/
public class TemplateArrayNode extends TemplateNode {
private List<TemplateNode> members = new ArrayList<>();
public TemplateArrayNode(JsonLocation startLocation) {
setStartLocation(startLocation);
}
public List<TemplateNode> getMembers() {
return members;
}
public void add(TemplateNode node) {
TemplateIndexNode indexNode = new TemplateIndexNode(members.size());
indexNode.setParent(this);
node.setParent(indexNode);
members.add(node);
}
public TemplateNode get(int index) {
return members.get(index);
}
}
| 8,078 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/TemplateNode.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import com.amazonaws.eclipse.cloudformation.templates.TemplateNodePath.PathNode;
import com.fasterxml.jackson.core.JsonLocation;
/**
* Abstract base class representing a generic JSON node in a Template document.
*/
public abstract class TemplateNode {
public static final String ROOT_PATH = "ROOT";
public static final String PATH_SEPARATOR = "/";
private TemplateNode parent;
private JsonLocation startLocation;
private JsonLocation endLocation;
public TemplateNode getParent() {
return parent;
}
public void setParent(TemplateNode parent) {
this.parent = parent;
}
public String getPath() {
List<PathNode> subPaths = getSubPaths();
StringBuilder builder = new StringBuilder();
for (PathNode subPath : subPaths) {
builder.append(subPath.getReadiblePath() + TemplateNode.PATH_SEPARATOR);
}
return builder.toString();
}
public List<PathNode> getSubPaths() {
Stack<PathNode> stack = new Stack<>();
TemplateNode node = parent;
while (node != null) {
if (node instanceof TemplateFieldNode) {
String fieldName = ((TemplateFieldNode) node).getText();
stack.push(new PathNode(fieldName));
} else if (node instanceof TemplateIndexNode) {
int index = ((TemplateIndexNode) node).getIndex();
stack.push(new PathNode(index));
} else if (node instanceof TemplateObjectNode) {
TemplateObjectNode objectNode = (TemplateObjectNode) node;
TemplateNode typeNode = objectNode.get("Type");
if (typeNode != null && typeNode instanceof TemplateValueNode) {
String type = ((TemplateValueNode) typeNode).getText();
node = node.getParent();
if (node == null) {
break;
}
if (!(node instanceof TemplateFieldNode)) {
continue;
}
String fieldName = ((TemplateFieldNode) node).getText();
stack.push(new PathNode(fieldName, type));
}
}
node = node.getParent();
}
stack.push(new PathNode(TemplateNode.ROOT_PATH));
List<PathNode> stackList = new ArrayList<>(stack);
Collections.reverse(stackList);
return Collections.unmodifiableList(stackList);
}
public JsonLocation getStartLocation() {
return startLocation;
}
public void setStartLocation(JsonLocation startLocation) {
this.startLocation = startLocation;
}
public JsonLocation getEndLocation() {
return endLocation;
}
public void setEndLocation(JsonLocation endLocation) {
this.endLocation = endLocation;
}
} | 8,079 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/TemplateNodeParser.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import com.amazonaws.eclipse.cloudformation.templates.TemplateNodePath.PathNode;
import com.amazonaws.eclipse.cloudformation.templates.editor.TemplateDocument;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Template parser to build the hierarchical TemplateNode tree. Ex:
* {
* "Resources": {
* "S3Bucket": {
* "Type": "AWS::S3::Bucket",
* "Properties": {
* ...
* }
* }
* },
* "Conditions": [
* {
* "Key": "somekey1",
* "Value": "somevalue1"
* },
* {
* "Key": "somekey2",
* "Value": "somevalue2"
* }
* ]
* }
*
* is to be parsed as the following structure:
*
* ROOT(O)
* |--> Resources(F) --> Resources(O)
* | +--> "S3Bucket"(F) --> AWS::S3::Bucket(O)
* | |--> Type(F) --> "AWS::S3::Bucket"(V)
* | +--> Properties(F) --> Properties(O)
* +--> Conditions(F) --> Conditions(A)
* |--> 0(I) --> Condition(O)
* | |--> Key(F) --> "somekey1"(V)
* | +--> Value(F) --> "somevalue1"(V)
* +--> 1(I) --> Condition(O)
* |--> Key(F) --> "somekey2"(V)
* +--> Value(F) --> "somevalue2"(V)
*
*** (O: Object node; F: Field node; A: Array node; I: Index node; V: Value node)
*
* If the document is not a valid Json file, the parser would record the {@link JsonParseException}
* and the {@link TemplateNodePath} to the position where error occurs.
*/
public class TemplateNodeParser {
private static final JsonFactory FACTORY = new ObjectMapper().getFactory();
private static final String ROOT_SCHEMA_OBJECT = TemplateNode.ROOT_PATH;
private JsonLocation lastLocation;
private JsonLocation currentLocation;
private final Stack<PathNode> path = new Stack<>();
private Exception exception;
// Test use only.
TemplateObjectNode parse(String document) throws Exception {
return parse(document, document.length());
}
private TemplateObjectNode parse(String document, int offset) throws Exception {
path.clear();
exception = null;
try {
JsonParser parser = FACTORY.createParser(document.substring(0, offset));
return parse(parser);
} catch (Exception e) {
exception = e;
throw e;
}
}
public TemplateObjectNode parse(TemplateDocument document, int offset) {
TemplateObjectNode node = null;
try {
node = parse(document.get(), offset);
document.setModel(node);
} catch (Exception e) {
// do nothing
} finally {
document.setSubPaths(getSubPaths());
}
return node;
}
public TemplateObjectNode parse(TemplateDocument document) {
return parse(document, document.getLength());
}
public Exception getJsonParseException() {
return exception;
}
public List<PathNode> getSubPaths() {
return Collections.unmodifiableList(path);
}
// Test use only
String getPath() {
List<PathNode> subPaths = getSubPaths();
StringBuilder builder = new StringBuilder();
for (PathNode subPath : subPaths) {
builder.append(String.format("%s%s", subPath.getReadiblePath(), TemplateNode.PATH_SEPARATOR));
}
return builder.toString();
}
/**
* Fetches the next token from the JsonParser. Also captures the location in
* the stream before and after fetching the token.
*
* @param parser
* The JsonParser objects from which the token has to be fetched.
* @return The JsonToken
*/
private JsonToken nextToken(JsonParser parser) throws IOException {
lastLocation = parser.getCurrentLocation();
JsonToken token = parser.nextToken();
currentLocation = parser.getCurrentLocation();
return token;
}
/**
* Returns the last location of the JsonParser.
*/
private JsonLocation getParserLastLocation(JsonParser parser) {
if (currentLocation != parser.getCurrentLocation()) {
getParserCurrentLocation(parser);
}
return lastLocation;
}
/**
* Returns the current location of the JsonParser.
*/
private JsonLocation getParserCurrentLocation(JsonParser parser) {
JsonLocation oldLocation = currentLocation;
currentLocation = parser.getCurrentLocation();
if (oldLocation != currentLocation) lastLocation = oldLocation;
return currentLocation;
}
/**
* Retrieves a JsonObject from the parser and creates a corresponding
* TemplateObjectNode. If the Json Object has an array or a child Json
* object, they are also parsed and associated with the TemplateObjectNode.
*
* @param parser
* The JsonParser from where the object has to be fetched.
* @return A TemplateObjectNode of the corresponding JsonObject.
*/
private TemplateObjectNode parseObject(JsonParser parser)
throws IOException {
JsonToken token = parser.getCurrentToken();
if (token != JsonToken.START_OBJECT)
throw new IllegalArgumentException(
"Current token not an object start token when attempting to parse an object: "
+ token);
TemplateObjectNode object = new TemplateObjectNode(
getParserCurrentLocation(parser));
do {
token = nextToken(parser);
if (token == JsonToken.END_OBJECT)
break;
if (token != JsonToken.FIELD_NAME)
throw new RuntimeException("Unexpected token: " + token);
String currentField = parser.getText();
push(new PathNode(currentField));
token = nextToken(parser);
if (token == JsonToken.START_OBJECT)
object.put(currentField, parseObject(parser));
if (token == JsonToken.START_ARRAY)
object.put(currentField, parseArray(parser));
if (token == JsonToken.VALUE_STRING)
object.put(currentField, parseValue(parser));
pop();
// we have to hack it here to mark the map key as a parameter in the path with the Type value for child schema
if (currentField.equals("Type") && object.get(currentField) instanceof TemplateValueNode) {
String value = ((TemplateValueNode) object.get(currentField)).getText();
PathNode mapKey = pop();
mapKey = new PathNode(mapKey.getFieldName(), value);
push(mapKey);
}
} while (true);
if (token != JsonToken.END_OBJECT)
throw new RuntimeException(
"Current token not an object end token: " + token);
object.setEndLocation(getParserCurrentLocation(parser));
return object;
}
/**
* Parses a given value string from the parser.
*
* @param parser
* The parser from where the value node has to be read.
* @return A TemplateValueNode object for the parsed value string.
*/
private TemplateValueNode parseValue(JsonParser parser) throws IOException,
JsonParseException {
TemplateValueNode node = new TemplateValueNode(parser.getText());
node.setStartLocation(getParserLastLocation(parser));
node.setEndLocation(getParserCurrentLocation(parser));
return node;
}
/**
* Parses a given array string from the parser.
*
* @param parser
* The parser from where the array has to be read.
* @return A TemplateArrayNode object for the parsed array.
*/
private TemplateArrayNode parseArray(JsonParser parser) throws IOException {
JsonToken token = parser.getCurrentToken();
if (token != JsonToken.START_ARRAY)
throw new IllegalArgumentException(
"Current token not an array start token when attempting to parse an array: "
+ token);
TemplateArrayNode array = new TemplateArrayNode(
getParserCurrentLocation(parser));
int index = 0;
do {
token = nextToken(parser);
if (token == JsonToken.END_ARRAY)
break;
push(new PathNode(index));
if (token == JsonToken.START_OBJECT)
array.add(parseObject(parser));
if (token == JsonToken.START_ARRAY)
array.add(parseArray(parser));
if (token == JsonToken.VALUE_STRING)
array.add(parseValue(parser));
pop();
++index;
} while (true);
if (token != JsonToken.END_ARRAY)
throw new RuntimeException("Current token not an array end token: "
+ token);
array.setEndLocation(getParserCurrentLocation(parser));
return array;
}
/**
* Parses the Json Object from the given JsonParser and returns the root node.
*
* @param parser The parser from where the array has to be read.
* @return The root node of the Json Object.
*/
private TemplateObjectNode parse(JsonParser parser) throws IOException {
nextToken(parser);
push(new PathNode(ROOT_SCHEMA_OBJECT));
TemplateObjectNode rootNode = parseObject(parser);
pop();
return rootNode;
}
/**
* Pushes the given token to the stack.
* @param token
*/
private void push(PathNode token){
path.push(token);
}
/**
* Pops a token from the stack.
* @return
*/
private PathNode pop(){
return path.pop();
}
}
| 8,080 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/TemplateFieldNode.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates;
public class TemplateFieldNode extends TemplateNode {
private final String text;
public TemplateFieldNode(String text) {
this.text = text;
}
public String getText() {
return text;
}
} | 8,081 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/Schema.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Schema {
private final Map<String, SchemaProperty> properties = new HashMap<>();
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void addProperty(String name, SchemaProperty property) {
properties.put(name, property);
}
public SchemaProperty getProperty(String property) {
return properties.get(property);
}
public Set<String> getProperties() {
return properties.keySet();
}
@Override
public String toString() {
String buffer = "";
for (Entry<String, SchemaProperty> entry : properties.entrySet()) {
buffer += " - " + entry.getKey() + ": " + entry.getValue() + "\n";
}
return buffer;
}
} | 8,082 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/SchemaProperty.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SchemaProperty {
private String description;
private String type;
private boolean required;
private List<String> allowedValues;
private Schema schema;
private boolean disableRefs = false;
private Map<String, Schema> childSchemas;
private String schemaLookupProperty;
private Schema defaultChildSchema;
public String getSchemaLookupProperty() {
return schemaLookupProperty;
}
public SchemaProperty(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean b) {
this.required = b;
}
public List<String> getAllowedValues() {
return allowedValues;
}
public void setAllowedValues(List<String> allowedValues) {
this.allowedValues = allowedValues;
}
public Map<String, Schema> getChildSchemas() {
return childSchemas;
}
public Schema getChildSchema(String id) {
return childSchemas.get(id);
}
public void setSchemaLookupProperty(String schemaLookupProperty) {
this.schemaLookupProperty = schemaLookupProperty;
}
public void addChildSchema(String name, Schema schema) {
if (childSchemas == null) childSchemas = new HashMap<>();
childSchemas.put(name, schema);
}
public void setDisableRefs(boolean b) {
this.disableRefs = b;
}
public boolean getDisableRefs() {
return disableRefs;
}
public Schema getSchema() {
return schema;
}
public void setSchema(Schema schema) {
this.schema = schema;
}
@Override
public String toString() {
return "(" + type + "): " + description;
}
public void setDefaultChildSchema(Schema defaultChildSchema) {
this.defaultChildSchema = defaultChildSchema;
}
public Schema getDefaultChildSchema() {
return defaultChildSchema;
}
} | 8,083 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/IntrinsicFunction.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema;
public class IntrinsicFunction {
private final String name;
private final String parameter;
private final String description;
public IntrinsicFunction(String name, String parameter, String description) {
this.name = name;
this.parameter = parameter;
this.description = description;
}
public String getName() {
return name;
}
public String getParameter() {
return parameter;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return name + " (" + parameter + "): " + description;
}
} | 8,084 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/TemplateSchemaRules.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TemplateSchemaRules {
// JSON Keys
private static final String ALLOWED_VALUES = "allowed-values";
private static final String CHILD_SCHEMAS = "child-schemas";
private static final String DEFAULT_CHILD_SCHEMA = "default-child-schema";
private static final String DESCRIPTION = "description";
private static final String INTRINSIC_FUNCTIONS = "intrinsic-functions";
private static final String PARAMETER = "parameter";
private static final String PROPERTIES = "properties";
private static final String PSEUDO_PARAMETERS = "pseudo-parameters";
private static final String REQUIRED = "required";
private static final String RESOURCES = "Resources";
private static final String ROOT_SCHEMA_OBJECT = "root-schema-object";
private static final String SCHEMA_LOOKUP_PROPERTY = "schema-lookup-property";
private static final String TYPE = "type";
// Template URL
private static final String TEMPLATE_SCHEMA_LOCATION = "http://vstoolkit.amazonwebservices.com/CloudFormationSchema/CloudFormationV1.schema";
private JsonNode rootNode;
private static TemplateSchemaRules instance;
private void parse() throws Exception {
ObjectMapper mapper = new ObjectMapper();
rootNode = mapper.readValue(new URL(TEMPLATE_SCHEMA_LOCATION), JsonNode.class);
}
public Set<String> getResourceTypeNames() {
return getTopLevelSchema().getProperty(RESOURCES).getChildSchemas().keySet();
}
public Schema getTopLevelSchema() {
Schema schema = parseSchema(this.rootNode.get(ROOT_SCHEMA_OBJECT));
return schema;
}
public List<PseudoParameter> getPseudoParameters() {
// TODO: Caching
ArrayList<PseudoParameter> pseudoParameters = new ArrayList<>();
Iterator<Entry<String, JsonNode>> iterator = rootNode.get(PSEUDO_PARAMETERS).fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> entry = iterator.next();
pseudoParameters.add(new PseudoParameter(entry.getKey(),
entry.getValue().get(TYPE).asText(),
entry.getValue().get(DESCRIPTION).asText()));
}
return pseudoParameters;
}
public List<IntrinsicFunction> getIntrinsicFuntions() {
// TODO: Caching
ArrayList<IntrinsicFunction> intrinsicFunctions = new ArrayList<>();
Iterator<Entry<String, JsonNode>> iterator = rootNode.get(INTRINSIC_FUNCTIONS).fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> entry = iterator.next();
intrinsicFunctions.add(new IntrinsicFunction(entry.getKey(),
entry.getValue().get(PARAMETER).asText(),
entry.getValue().get(DESCRIPTION).asText()));
}
return intrinsicFunctions;
}
private Schema parseSchema(JsonNode schemaNode) {
Schema schema = new Schema();
if (schemaNode.has(DESCRIPTION)) {
schema.setDescription(schemaNode.get(DESCRIPTION).textValue());
}
if (schemaNode.has(PROPERTIES)) {
Iterator<Entry<String, JsonNode>> fields = schemaNode.get(PROPERTIES).fields();
while (fields.hasNext()) {
Entry<String, JsonNode> entry = fields.next();
SchemaProperty schemaProperty = new SchemaProperty(entry.getValue().get(TYPE).asText());
if (entry.getValue().has(DESCRIPTION)) {
schemaProperty.setDescription(entry.getValue().get(DESCRIPTION).asText());
}
if (entry.getValue().has(REQUIRED)) {
schemaProperty.setRequired(entry.getValue().get(REQUIRED).asBoolean());
}
if (entry.getValue().has(ALLOWED_VALUES)) {
List<String> allowedValues = new ArrayList<>();
Iterator<JsonNode> iterator = entry.getValue().get(ALLOWED_VALUES).elements();
while (iterator.hasNext()) allowedValues.add(iterator.next().asText());
schemaProperty.setAllowedValues(allowedValues);
}
schema.addProperty(entry.getKey(), schemaProperty);
JsonNode node = entry.getValue();
if (node.has(DEFAULT_CHILD_SCHEMA)) {
Schema defaultSchema = parseSchema(node.get(DEFAULT_CHILD_SCHEMA));
schemaProperty.setDefaultChildSchema(defaultSchema);
} else if (node.has(PROPERTIES)) {
Schema defaultSchema = parseSchema(node);
schemaProperty.setSchema(defaultSchema);
}
if (node.has(SCHEMA_LOOKUP_PROPERTY)) {
schemaProperty.setSchemaLookupProperty(node.get(SCHEMA_LOOKUP_PROPERTY).asText());
}
if (node.has(CHILD_SCHEMAS)) {
Iterator<Entry<String, JsonNode>> fields2 = node.get(CHILD_SCHEMAS).fields();
while (fields2.hasNext()) {
Entry<String, JsonNode> entry2 = fields2.next();
String schemaName = entry2.getKey();
Schema schema2 = parseSchema(entry2.getValue());
schemaProperty.addChildSchema(schemaName, schema2);
}
}
}
} else {
// JSON freeform text?
}
return schema;
}
public static TemplateSchemaRules getInstance() {
if (instance == null) {
instance = new TemplateSchemaRules();
try {
instance.parse();
} catch (Exception e) {
throw new RuntimeException("", e);
}
}
return instance;
}
}
| 8,085 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/Section.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema;
import java.util.HashMap;
import java.util.Map;
public class Section {
private final String description;
private final String type;
private final boolean required;
final Schema schema;
private boolean disableRefs = false;
Map<String, Schema> childSchemas;
private String schemaLookupProperty;
public Section(String type, String description, boolean required, Schema schema) {
this.type = type;
this.description = description;
this.required = required;
this.schema = schema;
}
public Map<String, Schema> getChildSchemas() {
return childSchemas;
}
public void setSchemaLookupProperty(String schemaLookupProperty) {
this.schemaLookupProperty = schemaLookupProperty;
}
public void addChildSchema(String name, Schema schema) {
if (childSchemas == null) childSchemas = new HashMap<>();
childSchemas.put(name, schema);
}
public void setDisableRefs(boolean b) {
this.disableRefs = b;
}
public boolean getDisableRefs() {
return disableRefs;
}
public String getDescription() {
return description;
}
public String getType() {
return type;
}
public boolean isRequired() {
return required;
}
public Schema getSchema() {
return schema;
}
} | 8,086 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/PseudoParameter.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema;
public class PseudoParameter {
private final String name;
private final String type;
private final String description;
public PseudoParameter(String name, String type, String description) {
this.name = name;
this.type = type;
this.description = description;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return name + " (" + type + "): " + description;
}
} | 8,087 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/v2/AllowedValue.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(using = DeserializerFactory.AllowedValuesDeserializer.class)
public class AllowedValue {
private static final AllowedValue TRUE = new AllowedValue("true", "true");
private static final AllowedValue FALSE = new AllowedValue("false", "false");
public static final List<AllowedValue> BOOLEAN_ALLOWED_VALUES =
Collections.unmodifiableList(Arrays.asList(TRUE, FALSE));
public static final String P_DISPLAY_LABEL = "display-label";
public static final String P_VALUE = "value";
private String displayLabel;
private String value;
public AllowedValue(@JsonProperty(P_DISPLAY_LABEL) String displayLabel,
@JsonProperty(P_VALUE) String value) {
this.displayLabel = displayLabel;
this.value = value;
}
public String getDisplayLabel() {
return displayLabel;
}
@JsonProperty(P_DISPLAY_LABEL)
public void setDisplayLabel(String displayLabel) {
this.displayLabel = displayLabel;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 8,088 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/v2/ReturnValue.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
public class ReturnValue {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 8,089 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/v2/TemplateSchemaParser.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
import java.io.IOException;
import java.net.URL;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TemplateSchemaParser {
private static final ObjectMapper MAPPER = new ObjectMapper();
// The shared Template URL
private static final String TEMPLATE_SCHEMA_LOCATION = "http://vstoolkit.amazonwebservices.com/CloudFormationSchema/CloudFormationV1.schema";
private static TemplateSchema defaultTemplateSchema;
static {
MAPPER.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
try {
defaultTemplateSchema = MAPPER.readValue(new URL(TEMPLATE_SCHEMA_LOCATION), TemplateSchema.class);
} catch (IOException e) {
CloudFormationPlugin.getDefault().logError("Failed to load and parse the underlying CloudFormation schema file.", e);
}
}
public static TemplateSchema getDefaultSchema() {
return defaultTemplateSchema;
}
}
| 8,090 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/v2/ElementType.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
public enum ElementType {
STRING("String", "\"\"", -1),
ARRAY("Array", "[]", -1),
NAMED_ARRAY("Named-Array", "{}", -1),
NUMBER("Number", "\"\"", -1),
BOOLEAN("Boolean", "\"\"", -1),
OBJECT("Object", "{}", -1),
RESOURCE("Resource", "{}", -1),
JSON("Json", "{}", -1),
;
private final String typeValue;
private final String insertionText;
private final int cursorOffset;
private ElementType(String typeValue, String insertionText, int cursorOffset) {
this.typeValue = typeValue;
this.insertionText = insertionText;
this.cursorOffset = cursorOffset;
}
public String getTypeValue() {
return typeValue;
}
public String getInsertionText() {
return insertionText;
}
public int getCursorOffset() {
return cursorOffset;
}
public static ElementType fromValue(String typeValue) {
for (ElementType elementType : ElementType.values()) {
if (elementType.getTypeValue().equalsIgnoreCase(typeValue)) {
return elementType;
}
}
return STRING;
}
}
| 8,091 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/v2/IntrinsicFunction.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
import com.fasterxml.jackson.annotation.JsonProperty;
public class IntrinsicFunction {
private String parameter;
private String returnType;
private String description;
private String skeleton;
public String getParameter() {
return parameter;
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
public String getReturnType() {
return returnType;
}
@JsonProperty("return-type")
public void setReturnType(String returnType) {
this.returnType = returnType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSkeleton() {
return skeleton;
}
public void setSkeleton(String skeleton) {
this.skeleton = skeleton;
}
}
| 8,092 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/v2/TemplateElement.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* A union type for all kinds of Template element
*/
public class TemplateElement {
// A fake template element to be returned when the underlying schema is not known
public static final TemplateElement GENERIC_RESOURCE_ELEMENT = new TemplateElement();
static {
GENERIC_RESOURCE_ELEMENT.setType(ElementType.OBJECT.getTypeValue());
TemplateElement type = new TemplateElement();
type.setType(ElementType.STRING.getTypeValue());
type.setRequired("true");
Map<String, TemplateElement> properties = new HashMap<>();
properties.put("Type", type);
GENERIC_RESOURCE_ELEMENT.setProperties(properties);
}
// Allowed values: Array, Boolean, ConditionDeclaration, ConditionDefinitions, DestinationCidrBlock,
// Json, Named-Array, Number, Object, Policy, Reference, Resource, String
private String type;
private String required; // Allowed values: true, false, Json
private List<AllowedValue> allowedValues;
private Boolean disableRefs;
private Boolean disableFunctions;
private String description;
private String arrayType;
// The attribute name to look for the child schema, must be an existing key of the childSchemas attribute
private String schemaLookupProperty;
private List<String> resourceRefType;
private List<ReturnValue> returnValues;
// All the child schemas for this Json node.
private Map<String, TemplateElement> childSchemas;
private TemplateElement defaultChildSchema;
private Map<String, TemplateElement> properties;
/** Irregular fields in the schema file, might need to remove these. */
private TemplateElement S3DestinationConfiguration;
private TemplateElement TextTransformation;
public TemplateElement getS3DestinationConfiguration() {
return S3DestinationConfiguration;
}
public void setS3DestinationConfiguration(TemplateElement s3DestinationConfiguration) {
S3DestinationConfiguration = s3DestinationConfiguration;
}
public TemplateElement getTextTransformation() {
return TextTransformation;
}
public void setTextTransformation(TemplateElement textTransformation) {
TextTransformation = textTransformation;
}
/** End irregular fields in the schema file. */
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRequired() {
return required;
}
public void setRequired(String required) {
this.required = required;
}
public List<AllowedValue> getAllowedValues() {
return allowedValues;
}
@JsonProperty("allowed-values")
public void setAllowedValues(List<AllowedValue> allowedValues) {
this.allowedValues = allowedValues;
}
public Boolean getDisableRefs() {
return disableRefs;
}
@JsonProperty("disable-refs")
public void setDisableRefs(Boolean disableRefs) {
this.disableRefs = disableRefs;
}
public Boolean getDisableFunctions() {
return disableFunctions;
}
@JsonProperty("disable-functions")
public void setDisableFunctions(Boolean disableFunctions) {
this.disableFunctions = disableFunctions;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getArrayType() {
return arrayType;
}
@JsonProperty("array-type")
public void setArrayType(String arrayType) {
this.arrayType = arrayType;
}
public String getSchemaLookupProperty() {
return schemaLookupProperty;
}
@JsonProperty("schema-lookup-property")
public void setSchemaLookupProperty(String schemaLookupProperty) {
this.schemaLookupProperty = schemaLookupProperty;
}
public List<String> getResourceRefType() {
return resourceRefType;
}
@JsonProperty("resource-ref-type")
public void setResourceRefType(List<String> resourceRefType) {
this.resourceRefType = resourceRefType;
}
public List<ReturnValue> getReturnValues() {
return returnValues;
}
@JsonProperty("return-values")
public void setReturnValues(List<ReturnValue> returnValues) {
this.returnValues = returnValues;
}
public Map<String, TemplateElement> getChildSchemas() {
return childSchemas;
}
@JsonProperty("child-schemas")
public void setChildSchemas(Map<String, TemplateElement> childSchemas) {
this.childSchemas = childSchemas;
}
public TemplateElement getDefaultChildSchema() {
return defaultChildSchema;
}
@JsonProperty("default-child-schema")
public void setDefaultChildSchema(TemplateElement defaultChildSchema) {
this.defaultChildSchema = defaultChildSchema;
}
public Map<String, TemplateElement> getProperties() {
return properties;
}
public void setProperties(Map<String, TemplateElement> properties) {
this.properties = properties;
}
}
| 8,093 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/v2/DeserializerFactory.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
/**
* Customized Deserializers.
*/
public class DeserializerFactory {
/**
* {@link AllowedValue} POJO in the Json document could be either from a string literal
* or a Json map.
*/
public static class AllowedValuesDeserializer extends StdDeserializer<AllowedValue> {
private static final long serialVersionUID = 1L;
public AllowedValuesDeserializer() {
this(null);
}
protected AllowedValuesDeserializer(Class<?> vc) {
super(vc);
}
@Override
public AllowedValue deserialize(JsonParser jp, DeserializationContext context)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
if (node.isTextual() || node.isNumber()) {
String text = node.asText();
return new AllowedValue(text, text);
} else if (node.isObject()) {
String displayLabel = node.get(AllowedValue.P_DISPLAY_LABEL).asText();
String value = node.get(AllowedValue.P_VALUE).asText();
return new AllowedValue(displayLabel, value);
}
throw new RuntimeException("Unrecognized AllowedValue pattern");
}
}
}
| 8,094 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/v2/TemplateSchema.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
import java.util.List;
import java.util.Map;
import com.amazonaws.eclipse.cloudformation.templates.TemplateNode;
import com.amazonaws.eclipse.cloudformation.templates.TemplateNodePath.PathNode;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Root POJO of CloudFormation Template schema.
*/
public class TemplateSchema {
private Map<String, IntrinsicFunction> intrinsicFunctions;
private Map<String, PseudoParameter> pseudoParameters;
private TemplateElement rootSchemaObject;
public Map<String, IntrinsicFunction> getIntrinsicFunctions() {
return intrinsicFunctions;
}
@JsonProperty("intrinsic-functions")
public void setIntrinsicFunctions(Map<String, IntrinsicFunction> intrinsicFunctions) {
this.intrinsicFunctions = intrinsicFunctions;
}
public Map<String, PseudoParameter> getPseudoParameters() {
return pseudoParameters;
}
@JsonProperty("pseudo-parameters")
public void setPseudoParameters(Map<String, PseudoParameter> pseudoParameters) {
this.pseudoParameters = pseudoParameters;
}
public TemplateElement getRootSchemaObject() {
return rootSchemaObject;
}
@JsonProperty("root-schema-object")
public void setRootSchemaObject(TemplateElement rootSchemaObject) {
this.rootSchemaObject = rootSchemaObject;
}
@JsonIgnore
public TemplateElement getTemplateElement(List<PathNode> path) {
assert(path != null && !path.isEmpty() && path.get(0).equals(TemplateNode.ROOT_PATH));
TemplateElement currentElement = rootSchemaObject;
for (int i = 1; i < path.size(); ++i) {
PathNode currentPathNode = path.get(i);
// Current element is an Array, skip the path node
if (ElementType.fromValue(currentElement.getType()) == ElementType.ARRAY) {
String fieldName = currentPathNode.getFieldName();
if (fieldName != null && currentElement.getProperties() != null) {
currentElement = currentElement.getProperties().get(fieldName);
}
// Current element is an object with fixed attributes
} else if (currentElement.getProperties() != null) {
Map<String, TemplateElement> properties = currentElement.getProperties();
if (properties.containsKey(currentPathNode.getFieldName())) {
currentElement = properties.get(currentPathNode.getFieldName());
} else {
throw new RuntimeException("Cannot find TemplateElement: " + path);
}
// Current element is a map with fixed value schema
} else if (currentElement.getDefaultChildSchema() != null) {
currentElement = currentElement.getDefaultChildSchema();
// Current element is a map with dynamic value schema
} else if (currentElement.getChildSchemas() != null) {
Map<String, TemplateElement> childSchemas = currentElement.getChildSchemas();
List<String> parameters = currentPathNode.getParameters();
if (!parameters.isEmpty()) {
currentElement = childSchemas.get(parameters.get(0));
if (currentElement == null) {
throw new RuntimeException("Cannot find TemplateElement: " + path);
}
} else {
return TemplateElement.GENERIC_RESOURCE_ELEMENT;
}
} else {
throw new RuntimeException("Cannot find TemplateElement: " + path);
}
}
return currentElement;
}
}
| 8,095 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/schema/v2/PseudoParameter.java | /*
* Copyright 2017 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.schema.v2;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PseudoParameter {
private String type;
private String arrayType;
private String description;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getArrayType() {
return arrayType;
}
@JsonProperty("array-type")
public void setArrayType(String arrayType) {
this.arrayType = arrayType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 8,096 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/editor/TemplateContentAssistProcessor.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.editor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.CompletionProposal;
import org.eclipse.jface.text.contentassist.ContextInformation;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
import com.amazonaws.eclipse.cloudformation.templates.TemplateNode;
import com.amazonaws.eclipse.cloudformation.templates.TemplateNodeParser;
import com.amazonaws.eclipse.cloudformation.templates.TemplateNodePath.PathNode;
import com.amazonaws.eclipse.cloudformation.templates.TemplateObjectNode;
import com.amazonaws.eclipse.cloudformation.templates.schema.v2.AllowedValue;
import com.amazonaws.eclipse.cloudformation.templates.schema.v2.ElementType;
import com.amazonaws.eclipse.cloudformation.templates.schema.v2.TemplateElement;
import com.amazonaws.eclipse.cloudformation.templates.schema.v2.TemplateSchema;
import com.amazonaws.eclipse.cloudformation.templates.schema.v2.TemplateSchemaParser;
public class TemplateContentAssistProcessor implements IContentAssistProcessor {
private static final TemplateSchema TEMPLATE_SCHEMA = TemplateSchemaParser.getDefaultSchema();
private ICompletionProposal newFieldCompletionProposal(
TemplateDocument templateDocument, int offset, String fieldName,
TemplateElement schemaProperty, String stringToReplace) {
String insertionText = fieldName + "\" : ";
int finalCursorPosition = -1;
ElementType elementType = ElementType.fromValue(schemaProperty.getType());
if (elementType == null) {
IStatus status = new Status(IStatus.INFO,
CloudFormationPlugin.PLUGIN_ID, "Unhandled property type: "
+ schemaProperty.getType());
StatusManager.getManager().handle(status, StatusManager.LOG);
}
insertionText += elementType.getInsertionText();
finalCursorPosition = insertionText.length() + elementType.getCursorOffset();
if (finalCursorPosition == -1)
finalCursorPosition = insertionText.length();
int replacementOffset = offset - stringToReplace.length();
if ('"' == DocumentUtils.readToNextChar(templateDocument, offset)) {
stringToReplace += '"';
}
CompletionProposal proposal = newCompletionProposal(replacementOffset,
fieldName, insertionText, finalCursorPosition,
schemaProperty.getDescription(), stringToReplace);
return proposal;
}
/**
* Creates a new completion proposal with the given parameters.
*
* @param offset
* The starting position for the string to be inserted.
* @param label
* The label to displayed in the the proposal.
* @param insertionText
* The text to be inserted when a proposal is selected.
* @param finalCursorPosition
* The final cursor position after inserting the proposal.
* @param description
* The description for the proposal to be displayed in the tool
* tip.
* @param stringToReplace The string to be replaced when a proposal is selected.
*/
private CompletionProposal newCompletionProposal(int offset,
String label, String insertionText, int finalCursorPosition,
String description,String stringToReplace) {
IContextInformation contextInfo = new ContextInformation(label, label);
return new CompletionProposal(insertionText, offset, stringToReplace.length(),
finalCursorPosition, null, label, contextInfo, description);
}
private void provideAttributeAutoCompletions(
TemplateDocument document,
int offset,
TemplateElement element,
TemplateNode node,
List<ICompletionProposal> proposals) {
String stringToReplace = DocumentUtils.readToPreviousQuote(document, offset);
if (stringToReplace == null) {
return;
}
if (element.getProperties() != null) {
List<String> properties = new ArrayList<>(element.getProperties().keySet());
Collections.sort(properties);
Set<String> existingFields = new HashSet<>();
if (node instanceof TemplateObjectNode) {
TemplateObjectNode objectNode = (TemplateObjectNode) node;
for (Entry<String, TemplateNode> entry : objectNode.getFields()) {
existingFields.add(entry.getKey());
}
}
for (String property : properties) {
if (existingFields.contains(property)) {
continue;
}
if (!property.toLowerCase().startsWith(stringToReplace.toLowerCase())) {
continue;
}
proposals.add(newFieldCompletionProposal(document, offset,
property, element.getProperties().get(property), stringToReplace));
}
}
}
private void provideAllowedValueAutoCompletions(
TemplateDocument document,
int offset,
TemplateElement element,
List<PathNode> subPaths,
List<ICompletionProposal> proposals) {
String stringToReplace = DocumentUtils.readToPreviousQuote(document, offset);
if (stringToReplace == null) {
return;
}
List<AllowedValue> allowedValues = null;
if (ElementType.BOOLEAN == ElementType.fromValue(element.getType())) {
allowedValues = AllowedValue.BOOLEAN_ALLOWED_VALUES;
} else if (element.getAllowedValues() != null) {
allowedValues = element.getAllowedValues();
} else if (subPaths.size() > 2 && subPaths.get(subPaths.size() - 1).getFieldName().equals("Type")) {
List<PathNode> path = subPaths.subList(0, subPaths.size() - 2);
TemplateElement templateElement = TEMPLATE_SCHEMA.getTemplateElement(path);
allowedValues = new ArrayList<>();
if (templateElement.getChildSchemas() != null) {
Set<String> keySet = templateElement.getChildSchemas().keySet();
for (String key : keySet) {
allowedValues.add(new AllowedValue(
templateElement.getChildSchemas().get(key).getProperties().get("Type").getDescription(), key));
}
}
}
if (allowedValues != null && !allowedValues.isEmpty()) {
for (AllowedValue allowedValue : allowedValues) {
if (!allowedValue.getValue().toLowerCase().startsWith(stringToReplace.toLowerCase())) {
continue;
}
CompletionProposal proposal = newCompletionProposal(
offset - stringToReplace.length(), allowedValue.getValue(), allowedValue.getValue(),
allowedValue.getValue().length(), allowedValue.getDisplayLabel(), stringToReplace);
proposals.add(proposal);
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#
* computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
*/
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
List<ICompletionProposal> proposals = new ArrayList<>();
TemplateDocument document = (TemplateDocument) viewer.getDocument();
new TemplateNodeParser().parse(document, offset);
List<PathNode> subPaths = document.getSubPaths(offset);
TemplateElement templateElement = TEMPLATE_SCHEMA.getTemplateElement(subPaths);
TemplateNode templateNode = document.lookupNodeByPath(subPaths);
// The prefix for the string to be completed
String stringToReplace = DocumentUtils.readToPreviousQuote(document, offset);
if (stringToReplace != null) {
Character previousChar = DocumentUtils.readToPreviousChar(document, offset - stringToReplace.length() - 1);
Character unmatchedOpenBrace = DocumentUtils.readToPreviousUnmatchedOpenBrace(document, offset - stringToReplace.length() - 1);
if (previousChar == ':' || unmatchedOpenBrace == '[') {
provideAllowedValueAutoCompletions(document, offset, templateElement, subPaths, proposals);
} else if (unmatchedOpenBrace == '{') {
provideAttributeAutoCompletions(document, offset, templateElement, templateNode, proposals);
}
}
return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
@Override
public char[] getCompletionProposalAutoActivationCharacters() {
return new char[] { '"' };
}
@Override
public IContextInformation[] computeContextInformation(ITextViewer viewer,
int offset) {
// TODO Auto-generated method stub
return null;
}
@Override
public char[] getContextInformationAutoActivationCharacters() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getErrorMessage() {
// TODO Auto-generated method stub
return null;
}
@Override
public IContextInformationValidator getContextInformationValidator() {
// TODO Auto-generated method stub
return null;
}
} | 8,097 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/editor/TemplateAutoEditStrategy.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.editor;
import java.util.Arrays;
import java.util.Stack;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
/**
* Indentation strategy reacts to newlines or open characters by inserting the appropriate amount
* of indentation and moving the caret to the appropriate location. We apply the auto-edit strategy
* in the following two situations:
*
* 1. Newline character
* // See {@link IndentType} for more information.
* - Double indent
* - Open indent
* - Close indent
* - Jump out
* 2. Open character - includes {, [, (, ", '
*/
final class TemplateAutoEditStrategy implements IAutoEditStrategy {
// TODO to move this to preference page setting
static final int INDENTATION_LENGTH = 2;
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org
* .eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
@Override
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
try {
if (isNewlineCommand(command.text)) {
IndentContext context = getCurrentIndentContext(document, command);
if (context == null) {
return;
}
switch (context.indentType) {
case JUMP_OUT:
command.text = "";
command.caretOffset = command.offset + context.indentValue;
break;
case DOUBLE_INDENT:
command.text += sameCharSequence(' ', context.indentValue);
int length = command.text.length();
command.text += LINE_SEPARATOR + sameCharSequence(' ', Math.max(context.indentValue - INDENTATION_LENGTH, 0));
command.shiftsCaret = false;
command.caretOffset = command.offset + length;
break;
case OPEN_INDENT:
case CLOSE_INDENT:
default:
command.text += sameCharSequence(' ', context.indentValue);
command.shiftsCaret = true;
break;
}
} else if (PairType.isOpenCharacter(command.text)) {
insertClosingCharacter(document, command, PairType.fromValue(command.text).closeChar);
}
} catch (Exception e) {
CloudFormationPlugin.getDefault().logError("Error in auto edit:", e);
}
}
private void insertClosingCharacter(IDocument document, DocumentCommand command, String closingChar) throws BadLocationException {
String insertionText = closingChar;
if (needsTrailingComma(document, command)) {
insertionText += ",";
}
command.text += insertionText;
command.shiftsCaret = false;
command.caretOffset = command.offset + 1;
}
/**
* Return true if the next non-whitespace character is an open character, i.e {, [, (, ", '
*/
private boolean needsTrailingComma(IDocument document, DocumentCommand command) throws BadLocationException {
PairType pairType = PairType.fromValue(command.text);
// If the pair is single quote, or parentheses which are not Json token, we don't append the trailing comma.
if (pairType == null || !pairType.isJsonToken) {
return false;
}
int position = command.offset;
while (document.getLength() > position) {
String nextChar = document.get(position, 1);
if (PairType.isOpenCharacter(nextChar) && PairType.fromValue(nextChar).isJsonToken) {
return true;
} else if (!Character.isWhitespace(nextChar.charAt(0))) {
return false;
}
++position;
}
return false;
}
private static String sameCharSequence(char character, int length) {
char[] sequence = new char[length];
Arrays.fill(sequence, character);
return new String(sequence);
}
private static boolean isNewlineCommand(String characters) {
return characters.startsWith("\r") || characters.startsWith("\n");
}
private static IndentContext getCurrentIndentContext(IDocument document, DocumentCommand command) throws BadLocationException {
int offset = command.offset;
while (offset > 0) {
IRegion region = document.getLineInformationOfOffset(offset);
String lineContents = document.get(region.getOffset(), region.getLength());
IndentContext context = parseOneLine(lineContents, offset - region.getOffset());
if (context == null) {
offset = region.getOffset() - 1;
} else {
return context;
}
}
return null;
}
/**
* Parse the current line of the document and return an IndentContext for further action.
*
* @param line - The current line of the document.
* @param offset - The offset of the caret.
* @return - The IndentContext to be used for further action.
*/
static IndentContext parseOneLine(String line, int offset) {
int indent = leadingWhitespaceLength(line, 0, offset);
if (indent >= offset) {
return null;
}
Integer openIndex = parseLineLeftToRight(line, indent, offset - indent);
Integer closeIndex = parseLineRightToLeft(line, offset, line.length() - offset);
if (openIndex == null && closeIndex == null) {
return new IndentContext(IndentType.OPEN_INDENT, indent);
} else if (openIndex == null && closeIndex != null) {
if (leadingWhitespaceLength(line, offset, closeIndex - offset) == closeIndex - offset) {
return new IndentContext(IndentType.CLOSE_INDENT, Math.max(indent - INDENTATION_LENGTH, 0));
} else {
return new IndentContext(IndentType.OPEN_INDENT, indent);
}
} else if (openIndex != null && closeIndex == null) {
return new IndentContext(IndentType.OPEN_INDENT, indent + INDENTATION_LENGTH);
} else {
PairType type = PairType.fromValues(line.charAt(openIndex), line.charAt(closeIndex));
if (type == null) {
return new IndentContext(IndentType.OPEN_INDENT, indent);
} else if (type.needIndent) {
boolean adjencentToOpenChar = leadingWhitespaceLength(line, openIndex + 1, offset - openIndex - 1) == offset - openIndex - 1;
boolean adjencentToCloseChar = leadingWhitespaceLength(line, offset, closeIndex - offset) == closeIndex - offset;
if (adjencentToOpenChar && adjencentToCloseChar) {
return new IndentContext(IndentType.DOUBLE_INDENT, indent + INDENTATION_LENGTH);
} else if (adjencentToCloseChar) {
return new IndentContext(IndentType.CLOSE_INDENT, indent);
} else {
return new IndentContext(IndentType.OPEN_INDENT, indent + INDENTATION_LENGTH);
}
} else {
indent = closeIndex - offset + 1;
return new IndentContext(IndentType.JUMP_OUT, indent);
}
}
}
private static int leadingWhitespaceLength(String line, int offset, int length) {
assert(offset + length <= line.length());
int i = offset;
while (offset + length > i && Character.isWhitespace(line.charAt(i))) {
++i;
}
return i - offset;
}
/**
* Parse a line of string and return the index of the last unpaired character.
* Ex.
* - {"key":"value returns "
* - {"key":"value" returns {
* - {"key":["value" returns [
*/
private static Integer parseLineLeftToRight(String line, int offset, int length) {
if (length <= 0) {
return null;
}
Stack<Integer> stack = new Stack<>();
for (int i = offset; i < offset + length; ++i) {
PairType type = PairType.fromValue(line.charAt(i));
if (type == null) {
continue;
}
if (stack.isEmpty()) {
if (PairType.isOpenCharacter(line.charAt(i))) {
stack.push(i);
}
} else {
char lastCharInStack = line.charAt(stack.peek());
if (PairType.fromValues(lastCharInStack, line.charAt(i)) != null) {
stack.pop();
} else if (PairType.isOpenCharacter(line.charAt(i))) {
stack.push(i);
}
}
}
return stack.isEmpty() ? null : stack.pop();
}
/**
* Parse a line of string and return the first unpaired character.
* Ex.
* - value"} returns "
* - , "key2":"value2"} returns }
* - , "value2"]} returns ]
*/
private static Integer parseLineRightToLeft(String line, int offset, int length) {
if (length <= 0) {
return null;
}
Stack<Integer> stack = new Stack<>();
for (int i = offset + length - 1; i >= offset; --i) {
PairType type = PairType.fromValue(line.charAt(i));
if (type == null) {
continue;
}
if (stack.isEmpty()) {
if (PairType.isCloseCharacter(line.charAt(i))) {
stack.push(i);
}
} else {
char lastCharInStack = line.charAt(stack.peek());
if (PairType.fromValues(line.charAt(i), lastCharInStack) != null) {
stack.pop();
} else if (PairType.isCloseCharacter(line.charAt(i))) {
stack.push(i);
}
}
}
return stack.isEmpty() ? null : stack.pop();
}
static class IndentContext {
IndentType indentType;
int indentValue;
public IndentContext(IndentType indentType, int indentValue) {
this.indentType = indentType;
this.indentValue = indentValue;
}
}
// Indent types when typing 'return' key
static enum IndentType {
// '|' stands for cursor
DOUBLE_INDENT, // {|} => {\n |\n}
OPEN_INDENT, // {|"key":"value"} => {\n |"key":"value"}
CLOSE_INDENT, // {"key":"value"|} => {"key":"value"\n|}
SHIFT_INDENT, // | "key":"value" =>
JUMP_OUT, // {"key":"val|ue"} => {"key":"value"|}
;
}
private static enum PairType {
BRACES("{", "}", true, true),
BRACKETS("[", "]", true, true),
PARENTHESES("(", ")", false, false),
QUOTES("\"", "\"", false, true),
SINGLE_QUOTES("'", "'", false, false)
;
private PairType(String openChar, String closeChar, boolean needIndent, boolean isJsonToken) {
this.openChar = openChar;
this.closeChar = closeChar;
this.needIndent = needIndent;
this.isJsonToken = isJsonToken;
}
String openChar;
String closeChar;
boolean needIndent;
boolean isJsonToken;
static PairType fromValue(String character) {
for (PairType pair : PairType.values()) {
if (pair.openChar.equals(character) || pair.closeChar.equals(character)) {
return pair;
}
}
return null;
}
static PairType fromValue(char character) {
return fromValue(String.valueOf(character));
}
static boolean isOpenCharacter(String character) {
for (PairType pair : PairType.values()) {
if (pair.openChar.equals(character)) {
return true;
}
}
return false;
}
static boolean isOpenCharacter(char character) {
return isOpenCharacter(String.valueOf(character));
}
static boolean isCloseCharacter(String character) {
for (PairType pair : PairType.values()) {
if (pair.closeChar.equals(character)) {
return true;
}
}
return false;
}
static boolean isCloseCharacter(char character) {
return isCloseCharacter(String.valueOf(character));
}
static PairType fromValues(String open, String close) {
for (PairType pair : PairType.values()) {
if (pair.openChar.equals(open) && pair.closeChar.equals(close)) {
return pair;
}
}
return null;
}
static PairType fromValues(char open, char close) {
return fromValues(String.valueOf(open), String.valueOf(close));
}
}
} | 8,098 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.cloudformation/src/com/amazonaws/eclipse/cloudformation/templates/editor/TemplateSourceViewerConfiguration.java | /*
* Copyright 2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.cloudformation.templates.editor;
import java.util.Iterator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ContentAssistEvent;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.ICompletionListener;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.reconciler.MonoReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import com.amazonaws.eclipse.cloudformation.CloudFormationPlugin;
public final class TemplateSourceViewerConfiguration extends SourceViewerConfiguration {
private final TemplateScanner templateScanner;
public TemplateSourceViewerConfiguration() {
this(CloudFormationPlugin.getDefault().getPreferenceStore());
}
public TemplateSourceViewerConfiguration(IPreferenceStore store) {
templateScanner = new TemplateScanner(store);
}
public void handlePropertyChange(PropertyChangeEvent event) {
templateScanner.resetTokens();
}
@Override
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
PresentationReconciler reconciler = new PresentationReconciler();
DefaultDamagerRepairer damagerRepairer = new DefaultDamagerRepairer(templateScanner);
reconciler.setDamager(damagerRepairer, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(damagerRepairer, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
return reconciler;
}
@Override
public IReconciler getReconciler(ISourceViewer sourceViewer) {
TemplateReconcilingStrategy reconcilingStrategy = new TemplateReconcilingStrategy(sourceViewer);
MonoReconciler reconciler = new MonoReconciler(reconcilingStrategy, false);
reconciler.install(sourceViewer);
return reconciler;
}
@Override
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new IAnnotationHover() {
@Override
public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) {
IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
Iterator<?> iterator = annotationModel.getAnnotationIterator();
try {
IRegion lineInfo = sourceViewer.getDocument().getLineInformation(lineNumber);
while (iterator.hasNext()) {
Annotation annotation = (Annotation)iterator.next();
Position position = annotationModel.getPosition(annotation);
if (position.offset >= lineInfo.getOffset() &&
position.offset <= (lineInfo.getOffset() + lineInfo.getLength())) {
return annotation.getText();
}
}
} catch (BadLocationException e) { }
return null;
}
};
}
// Overriding to turn on text wrapping
@Override
public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
@Override
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, SWT.WRAP, null);
}
};
}
@Override
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
final ContentAssistant assistant = new ContentAssistant();
assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
assistant.setContentAssistProcessor(new TemplateContentAssistProcessor(), IDocument.DEFAULT_CONTENT_TYPE);
assistant.setAutoActivationDelay(0);
assistant.enableAutoActivation(true);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
assistant.enablePrefixCompletion(true);
assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY);
assistant.addCompletionListener(new ICompletionListener() {
@Override
public void assistSessionStarted(ContentAssistEvent event) {
assistant.showContextInformation();
}
@Override
public void assistSessionEnded(ContentAssistEvent event) {}
@Override
public void selectionChanged(ICompletionProposal proposal, boolean smartToggle) {}
});
assistant.setProposalSelectorBackground(
Display.getDefault().
getSystemColor(SWT.COLOR_WHITE));
return assistant;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getAutoEditStrategies(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
*/
@Override
public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) {
return new IAutoEditStrategy[] { new TemplateAutoEditStrategy() };
}
} | 8,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.