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.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/B_PutItemJsonTest.java
/* * Copyright 2014-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.services.dynamodbv2.document.quickstart; import org.junit.Test; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec; import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec; import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart; import com.amazonaws.services.dynamodbv2.document.utils.ValueMap; public class B_PutItemJsonTest extends AbstractQuickStart { @Test public void howToPutItems() { Table table = dynamo.getTable(TABLE_NAME); Item item = new Item() .withPrimaryKey(HASH_KEY_NAME, "B_PutItemJsonTest", RANGE_KEY_NAME, 1) // Store document as a map .withMap("document", new ValueMap() .withString("last_name", "Bar") .withString("first_name", "Jeff") .withString("current_city", "Tokyo") .withMap("next_haircut", new ValueMap() .withInt("year", 2014) .withInt("month", 10) .withInt("day", 30)) .withList("children", "SJB", "ASB", "CGB", "BGB", "GTB") ); table.putItem(item); // Retrieve the entire document and the entire document only Item documentItem = table.getItem(new GetItemSpec() .withPrimaryKey(HASH_KEY_NAME, "B_PutItemJsonTest", RANGE_KEY_NAME, 1) .withAttributesToGet("document")); System.out.println(documentItem.get("document")); // Output: {last_name=Bar, children=[SJB, ASB, CGB, BGB, GTB], first_name=Jeff, current_city=Tokyo, next_haircut={month=10, year=2014, day=30}} // Retrieve part of a document. Perhaps I need the next_haircut and nothing else Item partialDocItem = table.getItem(new GetItemSpec() .withPrimaryKey(HASH_KEY_NAME, "B_PutItemJsonTest", RANGE_KEY_NAME, 1) .withProjectionExpression("document.next_haircut")) ; System.out.println(partialDocItem); // Output: { Item: {document={next_haircut={month=10, year=2014, day=30}}} } // I can update part of a document. Here's how I would change my current_city back to Seattle: table.updateItem(new UpdateItemSpec() .withPrimaryKey(HASH_KEY_NAME, "B_PutItemJsonTest", RANGE_KEY_NAME, 1) .withUpdateExpression("SET document.current_city = :city") .withValueMap(new ValueMap().withString(":city", "Seattle")) ); // Retrieve the entire item Item itemUpdated = table.getItem(HASH_KEY_NAME, "B_PutItemJsonTest", RANGE_KEY_NAME, 1); System.out.println(itemUpdated); // Output: { Item: {document={last_name=Bar, children=[SJB, ASB, CGB, BGB, GTB], first_name=Jeff, current_city=Seattle, next_haircut={month=10, year=2014, day=30}}, myRangeKey=1, myHashKey=B_PutItemJsonTest} } } }
7,300
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/D_QueryTest.java
/* * Copyright 2014-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.services.dynamodbv2.document.quickstart; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.ItemCollection; import com.amazonaws.services.dynamodbv2.document.LowLevelResultListener; import com.amazonaws.services.dynamodbv2.document.QueryFilter; import com.amazonaws.services.dynamodbv2.document.QueryOutcome; import com.amazonaws.services.dynamodbv2.document.RangeKeyCondition; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart; import com.amazonaws.services.dynamodbv2.document.utils.NameMap; import com.amazonaws.services.dynamodbv2.document.utils.ValueMap; /** * Sample code to query items from DynamoDB table. */ public class D_QueryTest extends AbstractQuickStart { @Before public void before() { new B_PutItemTest().howToPutItems(); } @Test public void simpleQuery() { Table table = dynamo.getTable(TABLE_NAME); ItemCollection<?> col = table.query(HASH_KEY_NAME, "foo", new RangeKeyCondition(RANGE_KEY_NAME).between(1, 10)); int count = 0; for (Item item: col) { System.out.println(item); count++; } Assert.assertTrue(count == 10); } @Test public void howToUseQueryFilters() { Table table = dynamo.getTable(TABLE_NAME); ItemCollection<QueryOutcome> col = table.query(HASH_KEY_NAME, "foo", new RangeKeyCondition(RANGE_KEY_NAME).between(1, 10), new QueryFilter("intAttr").gt(1238)); int count = 0; QueryOutcome lastOutcome = null; for (Item item: col) { Assert.assertTrue(item.getInt("intAttr") > 1238); System.out.println(item); count++; // can retrieve the low level result if needed QueryOutcome lowLevelOutcome= col.getLastLowLevelResult(); if (lowLevelOutcome != lastOutcome) { System.out.println(lowLevelOutcome); lastOutcome = lowLevelOutcome; } } Assert.assertTrue(count > 0); Assert.assertTrue(count < 10); } @Test public void howToUseFilterExpression() { Table table = dynamo.getTable(TABLE_NAME); ItemCollection<QueryOutcome> col = table.query( HASH_KEY_NAME, "foo", new RangeKeyCondition(RANGE_KEY_NAME).between(1, 10), // filter expression "intAttr > :intAttr", // no attribute name substitution null, // attribute value substitution new ValueMap().withInt(":intAttr", 1238)); // can be notified of the low level result if needed col.registerLowLevelResultListener(new LowLevelResultListener<QueryOutcome>() { @Override public void onLowLevelResult(QueryOutcome outcome) { System.out.println(outcome); } }); int count = 0; for (Item item: col) { Assert.assertTrue(item.getInt("intAttr") > 1238); System.out.println(item); count++; } Assert.assertTrue(count > 0); Assert.assertTrue(count < 10); } @Test public void howToUseFilterExpression_AttrNameSubstitution() { Table table = dynamo.getTable(TABLE_NAME); ItemCollection<?> col = table.query( HASH_KEY_NAME, "foo", new RangeKeyCondition(RANGE_KEY_NAME).between(1, 10), // filter expression with name substitution "#intAttr > :intAttr", // attribute name substitution new NameMap().with("#intAttr", "intAttr"), // attribute value substitution new ValueMap().withInt(":intAttr", 1238)); int count = 0; for (Item item: col) { Assert.assertTrue(item.getInt("intAttr") > 1238); System.out.println(item); count++; } Assert.assertTrue(count > 0); Assert.assertTrue(count < 10); } @Test public void howToUseProjectionExpression() { Table table = dynamo.getTable(TABLE_NAME); ItemCollection<?> col = table.query( HASH_KEY_NAME, "foo", new RangeKeyCondition(RANGE_KEY_NAME).between(1, 10), // filter expression "#intAttr > :intAttr", // projection expression "intAttr, #binary", // attribute name substitution new NameMap() .with("#intAttr", "intAttr") .with("#binary", "binary"), // attribute value substitution new ValueMap().withInt(":intAttr", 1238)); int count = 0; for (Item item: col) { Assert.assertTrue(item.getInt("intAttr") > 1238); System.out.println(item); count++; } Assert.assertTrue(count > 0); Assert.assertTrue(count < 10); } }
7,301
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/A_CreateTableTest.java
/* * Copyright 2014-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.services.dynamodbv2.document.quickstart; import org.junit.Test; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.Projection; import com.amazonaws.services.dynamodbv2.model.ProjectionType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.model.TableDescription; /** * Sample code to create a DynamoDB table. */ public class A_CreateTableTest extends AbstractQuickStart { private final ProvisionedThroughput THRUPUT = new ProvisionedThroughput(1L, 2L); private final Projection PROJECTION = new Projection().withProjectionType(ProjectionType.ALL); /** * Sample request to create a DynamoDB table with an LSI and GSI that * can be accessed via a combination of hash keys and range keys. */ @Test public void howToCreateTable() throws InterruptedException { String TABLE_NAME = "myTableForMidLevelApi"; Table table = dynamo.getTable(TABLE_NAME); // check if table already exists, and if so wait for it to become active TableDescription desc = table.waitForActiveOrDelete(); if (desc != null) { System.out.println("Skip creating table which already exists and ready for use: " + desc); return; } // Table doesn't exist. Let's create it. table = dynamo.createTable(newCreateTableRequest(TABLE_NAME)); // Wait for the table to become active desc = table.waitForActive(); System.out.println("Table is ready for use! " + desc); } private CreateTableRequest newCreateTableRequest(String tableName) { // primary keys String HASH_KEY_NAME = "myHashKey"; String RANGE_KEY_NAME = "myRangeKey"; // local secondary index String LSI_NAME = "myLSI"; String LSI_RANGE_KEY_NAME = "myLsiRangeKey"; // global secondary index String RANGE_GSI_NAME = "myRangeGSI"; String GSI_HASH_KEY_NAME = "myGsiHashKey"; String GSI_RANGE_KEY_NAME = "myGsiRangeKey"; CreateTableRequest req = new CreateTableRequest() .withTableName(tableName) .withAttributeDefinitions( new AttributeDefinition(HASH_KEY_NAME, ScalarAttributeType.S), new AttributeDefinition(RANGE_KEY_NAME, ScalarAttributeType.N), new AttributeDefinition(LSI_RANGE_KEY_NAME, ScalarAttributeType.N), new AttributeDefinition(GSI_HASH_KEY_NAME, ScalarAttributeType.S), new AttributeDefinition(GSI_RANGE_KEY_NAME, ScalarAttributeType.N)) .withKeySchema( new KeySchemaElement(HASH_KEY_NAME, KeyType.HASH), new KeySchemaElement(RANGE_KEY_NAME, KeyType.RANGE)) .withProvisionedThroughput(THRUPUT) .withGlobalSecondaryIndexes( new GlobalSecondaryIndex() .withIndexName(RANGE_GSI_NAME) .withKeySchema( new KeySchemaElement(GSI_HASH_KEY_NAME, KeyType.HASH), new KeySchemaElement(GSI_RANGE_KEY_NAME, KeyType.RANGE)) .withProjection(PROJECTION) .withProvisionedThroughput(THRUPUT)) .withLocalSecondaryIndexes( new LocalSecondaryIndex() .withIndexName(LSI_NAME) .withKeySchema( new KeySchemaElement(HASH_KEY_NAME, KeyType.HASH), new KeySchemaElement(LSI_RANGE_KEY_NAME, KeyType.RANGE)) .withProjection(PROJECTION)) ; return req; } }
7,302
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/C_GetItemOutComeTest.java
/* * Copyright 2014-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.services.dynamodbv2.document.quickstart; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.amazonaws.services.dynamodbv2.document.GetItemOutcome; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec; import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart; import com.amazonaws.services.dynamodbv2.document.utils.NameMap; /** * Sample code to get item outcome from DynamoDB table. */ public class C_GetItemOutComeTest extends AbstractQuickStart { @Before public void before() { new B_PutItemTest().howToPutItems(); } @Test public void howToGetItemOutcomes() { Table table = dynamo.getTable(TABLE_NAME); for (int i=1; i <= 10; i++) { GetItemOutcome outcome = table.getItemOutcome( HASH_KEY_NAME, "foo", RANGE_KEY_NAME, i); Item item = outcome.getItem(); System.out.println("========== item " + i + " =========="); System.out.println(item); byte[] binary = item.getBinary("binary"); System.out.println("binary: " + Arrays.toString(binary)); Set<byte[]> binarySet = item.getBinarySet("binarySet"); for (byte[] ba: binarySet) { System.out.println("binary set element: " + Arrays.toString(ba)); } boolean bTrue = item.getBoolean("booleanTrue"); System.out.println("booleanTrue: " + bTrue); int intval = item.getInt("intAttr"); System.out.println("intAttr: " + intval); List<Object> listval = item.getList("listAtr"); System.out.println("listAtr: " + listval); Map<String,Object> mapval = item.getMap("mapAttr"); System.out.println("mapAttr: " + mapval); Object nullval = item.get("nullAttr"); System.out.println("nullAttr: " + nullval); BigDecimal numval = item.getNumber("numberAttr"); System.out.println("numberAttr: " + numval); String strval = item.getString("stringAttr"); System.out.println("stringAttr: " + strval); Set<String> strset = item.getStringSet("stringSetAttr"); System.out.println("stringSetAttr: " + strset); // "Outcome" allows access to the low level result System.out.println("low level result: " + outcome.getGetItemResult()); } } @Test public void howToUseProjectionExpression() { Table table = dynamo.getTable(TABLE_NAME); for (int i=1; i <= 10; i++) { GetItemOutcome outcome = table.getItemOutcome( HASH_KEY_NAME, "foo", RANGE_KEY_NAME, i, // Here is the projection expression to select 3 attributes // to be returned. // This expression requires attribute name substitution for // "binary" which is a reserved word in DynamoDB "#binary, intAttr, stringAttr", new NameMap().with("#binary", "binary")); Item item = outcome.getItem(); System.out.println("========== item " + i + " =========="); System.out.println(item); byte[] binary = item.getBinary("binary"); System.out.println("binary: " + Arrays.toString(binary)); int intval = item.getInt("intAttr"); System.out.println("intAttr: " + intval); Set<String> strset = item.getStringSet("stringSetAttr"); System.out.println("stringSetAttr: " + strset); // "Outcome" allows access to the low level result System.out.println("low level result: " + outcome.getGetItemResult()); } } @Test public void howToUseGetItemSpec() { Table table = dynamo.getTable(TABLE_NAME); for (int i=1; i <= 10; i++) { GetItemOutcome outcome = table.getItemOutcome(new GetItemSpec() .withPrimaryKey(HASH_KEY_NAME, "foo", RANGE_KEY_NAME, i) .withProjectionExpression("#binary, intAttr, stringAttr") .withNameMap(new NameMap().with("#binary", "binary"))); Item item = outcome.getItem(); System.out.println("========== item " + i + " =========="); System.out.println(item); byte[] binary = item.getBinary("binary"); System.out.println("binary: " + Arrays.toString(binary)); int intval = item.getInt("intAttr"); System.out.println("intAttr: " + intval); Set<String> strset = item.getStringSet("stringSetAttr"); System.out.println("stringSetAttr: " + strset); // "Outcome" allows access to the low level result System.out.println("low level result: " + outcome.getGetItemResult()); } } @Test public void getNonExistentItem() { Table table = dynamo.getTable(TABLE_NAME); GetItemOutcome outcome = table.getItemOutcome( HASH_KEY_NAME, "bar", RANGE_KEY_NAME, 99); Item item = outcome.getItem(); Assert.assertNull(item); // "Outcome" allows access to the low level result System.out.println("low level result: " + outcome.getGetItemResult()); } }
7,303
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/H_BatchGetItemTest.java
/* * Copyright 2014-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.services.dynamodbv2.document.quickstart; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.amazonaws.services.dynamodbv2.document.BatchGetItemOutcome; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.TableKeysAndAttributes; import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart; import com.amazonaws.services.dynamodbv2.document.utils.NameMap; import com.amazonaws.services.dynamodbv2.model.KeysAndAttributes; import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity; /** * Sample code to perform batch get items from DynamoDB. */ public class H_BatchGetItemTest extends AbstractQuickStart { @Before public void before() throws InterruptedException { new B_PutItemTest().howToPutItems(); F_UpdateItemTest.setupData(dynamo); } @Test public void howToBatchGet_FromOneTable() { TableKeysAndAttributes tableKeysAndAttributes = new TableKeysAndAttributes(TABLE_NAME) .withAttrbuteNames("binary", "booleanTrue", "intAttr", "mapAttr", "stringSetAttr") // you can add a bunch of keys in one go .addHashAndRangePrimaryKeys( HASH_KEY_NAME, RANGE_KEY_NAME, "foo", 1, "foo", 2, "foo", 3 // etc. ) // or you can take it slow and add one at a time .addHashAndRangePrimaryKey(HASH_KEY_NAME, "foo", RANGE_KEY_NAME, 4) .addHashAndRangePrimaryKey(HASH_KEY_NAME, "foo", RANGE_KEY_NAME, 5) ; BatchGetItemOutcome outcome = dynamo.batchGetItem( ReturnConsumedCapacity.TOTAL, tableKeysAndAttributes); Map<String, List<Item>> tableItems = outcome.getTableItems(); Assert.assertTrue(tableItems.size() == 1); for (Map.Entry<String, List<Item>> e: tableItems.entrySet()) { System.out.println("tableName: " + e.getKey()); for (Item item: e.getValue()) { System.out.println("item: " + item); } Assert.assertTrue(e.getValue().size() == 5); } } @Test public void howToUse_ProjectionExpression() { TableKeysAndAttributes tableKeysAndAttributes = new TableKeysAndAttributes(TABLE_NAME) // use projection expression instead of attribute names .withProjectionExpression( HASH_KEY_NAME + ", " + RANGE_KEY_NAME + ", " + "#binary, booleanTrue, intAttr, mapAttr, stringSetAttr") .withNameMap(new NameMap().with("#binary", "binary")) // you can add a bunch of keys in one go .addHashAndRangePrimaryKeys( HASH_KEY_NAME, RANGE_KEY_NAME, "foo", 2, "foo", 3, "foo", 4, "foo", 5 // etc. ); BatchGetItemOutcome outcome = dynamo.batchGetItem( ReturnConsumedCapacity.TOTAL, tableKeysAndAttributes); Map<String, List<Item>> tableItems = outcome.getTableItems(); Assert.assertTrue(tableItems.size() == 1); for (Map.Entry<String, List<Item>> e: tableItems.entrySet()) { System.out.println("tableName: " + e.getKey()); for (Item item: e.getValue()) { System.out.println("item: " + item); } Assert.assertTrue(e.getValue().size() == 4); } } @Test public void howToBatchGet_FromMultipleTables() { BatchGetItemOutcome outcome = dynamo.batchGetItem( // First table new TableKeysAndAttributes(TABLE_NAME) .withAttrbuteNames("binary", "booleanTrue", "intAttr", "mapAttr", "stringSetAttr") // you can add a bunch of keys in one go .addHashAndRangePrimaryKeys( HASH_KEY_NAME, RANGE_KEY_NAME, "foo", 1, "foo", 2, "foo", 3 // etc. ), // Second table new TableKeysAndAttributes(F_UpdateItemTest.TABLE_NAME) .withAttrbuteNames(F_UpdateItemTest.HASH_KEY, F_UpdateItemTest.RANGE_KEY, "AddressLine1", "city", "state", "zipcode", "phone") // you can add a bunch of keys in one go .addHashAndRangePrimaryKeys( F_UpdateItemTest.HASH_KEY, F_UpdateItemTest.RANGE_KEY, F_UpdateItemTest.FIRST_CUSTOMER_ID, F_UpdateItemTest.ADDRESS_TYPE_HOME, F_UpdateItemTest.FIRST_CUSTOMER_ID, F_UpdateItemTest.ADDRESS_TYPE_WORK // etc. ) ); Map<String, List<Item>> tableItems = outcome.getTableItems(); Assert.assertTrue(tableItems.size() == 2); for (Map.Entry<String, List<Item>> e: tableItems.entrySet()) { String tableName = e.getKey(); System.out.println("tableName: " + tableName); for (Item item: e.getValue()) { System.out.println("item: " + item); } if (tableName.equals(TABLE_NAME)) Assert.assertTrue(e.getValue().size() == 3); else Assert.assertTrue(e.getValue().size() == 2); } } @Test public void howToHandle_UnprocessedKeys() throws InterruptedException { TableKeysAndAttributes tableKeysAndAttributes = new TableKeysAndAttributes(TABLE_NAME) .withAttrbuteNames("binary", "booleanTrue", "intAttr", "mapAttr", "stringSetAttr") // you can add a bunch of keys in one go .addHashAndRangePrimaryKeys( HASH_KEY_NAME, RANGE_KEY_NAME, "foo", 1, "foo", 2, "foo", 3, "foo", 4, "foo", 5 // etc. ) ; // unprocessed items from DynamoDB int attempts = 0; Map<String, KeysAndAttributes> unprocessed = null ; do { if (attempts > 0) { // exponential backoff per DynamoDB recommendation Thread.sleep((1 << attempts) * 1000); } BatchGetItemOutcome outcome; if (unprocessed == null || unprocessed.size() > 0) { // handle initial request outcome = dynamo.batchGetItem(tableKeysAndAttributes); } else { // handle unprocessed items outcome = dynamo.batchGetItemUnprocessed(unprocessed); } Map<String, List<Item>> tableItems = outcome.getTableItems(); for (Map.Entry<String, List<Item>> e : tableItems.entrySet()) { System.out.println("tableName: " + e.getKey()); for (Item item : e.getValue()) { System.out.println("item: " + item); } Assert.assertTrue(e.getValue().size() == 5); } unprocessed = outcome.getUnprocessedKeys(); System.out.println("unprocessed: " + unprocessed); } while (unprocessed.size() > 0); } }
7,304
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/E_ScanTest.java
/* * Copyright 2014-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.services.dynamodbv2.document.quickstart; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.ItemCollection; import com.amazonaws.services.dynamodbv2.document.ScanFilter; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart; import com.amazonaws.services.dynamodbv2.document.utils.NameMap; import com.amazonaws.services.dynamodbv2.document.utils.ValueMap; /** * Sample code to scan items from DynamoDB table. */ public class E_ScanTest extends AbstractQuickStart { @Before public void before() { new B_PutItemTest().howToPutItems(); } @Test public void howToUseScanFilters() { Table table = dynamo.getTable(TABLE_NAME); ItemCollection<?> col = table.scan( new ScanFilter(HASH_KEY_NAME).eq("foo"), new ScanFilter(RANGE_KEY_NAME).between(1, 10) ); int count = 0; for (Item item: col) { System.out.println(item); count++; } Assert.assertTrue(count == 10); } @Test public void howToUseFilterExpression() { Table table = dynamo.getTable(TABLE_NAME); ItemCollection<?> col = table.scan( // filter expression "myHashKey = :myHashKey AND " + "myRangeKey BETWEEN :lo and :hi AND " + "intAttr > :intAttr", // no attribute name substitution null, // attribute value substitution new ValueMap() .withString(":myHashKey", "foo") .withInt(":lo", 1).withInt(":hi", 10) .withInt(":intAttr", 1238) ); int count = 0; for (Item item: col) { Assert.assertTrue(item.getInt("intAttr") > 1238); System.out.println(item); count++; } Assert.assertTrue(count > 0); Assert.assertTrue(count < 10); } @Test public void howToUseFilterExpression_AttrNameSubstitution() { Table table = dynamo.getTable(TABLE_NAME); ItemCollection<?> col = table.scan( // filter expression "myHashKey = :myHashKey AND " + "#myRangeKey BETWEEN :lo and :hi AND " + "intAttr > :intAttr", // attribute name substitution new NameMap().with("#myRangeKey", "myRangeKey"), // attribute value substitution new ValueMap() .withString(":myHashKey", "foo") .withInt(":lo", 1).withInt(":hi", 10) .withInt(":intAttr", 1238) ); int count = 0; for (Item item: col) { Assert.assertTrue(item.getInt("intAttr") > 1238); System.out.println(item); count++; } Assert.assertTrue(count > 0); Assert.assertTrue(count < 10); } @Test public void howToUseProjectionExpression() { Table table = dynamo.getTable(TABLE_NAME); ItemCollection<?> col = table.scan( // filter expression "myHashKey = :myHashKey AND " + "#myRangeKey BETWEEN :lo and :hi AND " + "intAttr > :intAttr", // projection expression "intAttr, #binary", // attribute name substitution new NameMap() .with("#myRangeKey", "myRangeKey") .with("#binary", "binary"), // attribute value substitution new ValueMap() .withString(":myHashKey", "foo") .withInt(":lo", 1).withInt(":hi", 10) .withInt(":intAttr", 1238) ); int count = 0; for (Item item: col) { Assert.assertTrue(item.getInt("intAttr") > 1238); System.out.println(item); count++; } Assert.assertTrue(count > 0); Assert.assertTrue(count < 10); } }
7,305
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/Z_DeleteTableTest.java
/* * Copyright 2014-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.services.dynamodbv2.document.quickstart; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart; import com.amazonaws.services.dynamodbv2.model.TableDescription; /** * Sample code to delete a DynamoDB table. */ public class Z_DeleteTableTest extends AbstractQuickStart { // @Test public void howToDeleteTable() throws InterruptedException { String TABLE_NAME = "myTableForMidLevelApi"; Table table = dynamo.getTable(TABLE_NAME); // Wait for the table to become active or deleted TableDescription desc = table.waitForActiveOrDelete(); if (desc == null) { System.out.println("Table " + table.getTableName() + " does not exist."); } else { table.delete(); // No need to wait, but you could table.waitForDelete(); System.out.println("Table " + table.getTableName() + " has been deleted"); } } }
7,306
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/JavaSdkPlugin.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.sdk.ui; import org.osgi.framework.BundleContext; import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin; /** * The activator class controls the plug-in life cycle */ public class JavaSdkPlugin extends AbstractAwsPlugin { /** The shared instance */ private static JavaSdkPlugin plugin; /** * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /** * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static JavaSdkPlugin getDefault() { return plugin; } }
7,307
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/FilenameFilters.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.sdk.ui; import java.io.File; import java.io.FilenameFilter; import java.util.regex.Pattern; /** * Collection of filename filters to pull out various files from the AWS SDK for * Java. */ public class FilenameFilters { private static final Pattern AWS_JAVA_SDK_PATTERN = Pattern.compile("aws-java-sdk-(\\d+|\\.)+\\.jar"); private static final Pattern AWS_JAVA_SDK_SOURCE_PATTERN = Pattern.compile("aws-java-sdk-(\\d+|\\.)+\\-sources\\.jar"); /** * Filename filter accepting jar files. */ public static class JarFilenameFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return (name.toLowerCase().endsWith(".jar")); } } /** * Filename filter accepting only the library jar from the AWS SDK for Java. */ public static class SdkLibraryJarFilenameFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return AWS_JAVA_SDK_PATTERN.matcher(name).matches(); } } /** * Filename filter accepting only the source jar from the AWS SDK for Java. */ public static class SdkSourceJarFilenameFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return AWS_JAVA_SDK_SOURCE_PATTERN.matcher(name).matches(); } } /** * Filename filter accepting only .java source files. */ public static class JavaSourceFilenameFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".java"); } } /** * Filename filter accepting only the credentials file. */ public static class CredentialsFilenameFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return name.equals("credentials"); } } }
7,308
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/SdkSample.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.sdk.ui; import org.eclipse.core.runtime.IPath; /** * Represents a sample included with a version of the AWS SDK for Java. */ public class SdkSample { private final String name; private final String description; private final IPath path; /** * Constructs a new SDK sample object with the given name, description and * location. * * @param sampleName * The name of this sample. * @param description * The description of this sample. * @param samplePath * The location of this sample. */ public SdkSample(String sampleName, String description, IPath samplePath) { this.name = sampleName; this.description = description; this.path = samplePath; } /** * Returns the location of the files for this sample. * * @return The location of the files included in this sample. */ public IPath getPath() { return path; } /** * Returns the name of this sample. * * @return The name of this sample. */ public String getName() { return name; } /** * Returns the description of this sample. * * @return The description of this sample. */ public String getDescription() { return description; } }
7,309
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/SdkOverviewSection.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.sdk.ui; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import com.amazonaws.eclipse.core.AwsUrls; import com.amazonaws.eclipse.core.ui.overview.OverviewSection; import com.amazonaws.eclipse.sdk.ui.wizard.NewAwsJavaProjectWizard; /** * AWS SDK for Java specific section on the AWS Toolkit for Eclipse overview page. */ public class SdkOverviewSection extends OverviewSection implements OverviewSection.V2 { private static final String SDK_FOR_JAVA_DEVELOPER_GUIDE_URL = "http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/welcome.html?" + AwsUrls.TRACKING_PARAMS; /** * @see com.amazonaws.eclipse.core.ui.overview.OverviewSection#createControls(org.eclipse.swt.widgets.Composite) */ @Override public void createControls(Composite parent) { Composite tasksSection = toolkit.newSubSection(parent, "Tasks"); toolkit.newListItem(tasksSection, "Create a New AWS Java Project", null, openNewAwsJavaProjectAction); Composite resourcesSection = toolkit.newSubSection(parent, "Additional Resources"); toolkit.newListItem(resourcesSection, "AWS SDK for Java Developer Guide", SDK_FOR_JAVA_DEVELOPER_GUIDE_URL); } /** Action to open the New AWS Java Project wizard in a dialog */ private static final IAction openNewAwsJavaProjectAction = new Action() { @Override public void run() { NewAwsJavaProjectWizard newWizard = new NewAwsJavaProjectWizard("Overview"); newWizard.init(PlatformUI.getWorkbench(), null); WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard); dialog.open(); } }; }
7,310
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/SdkSamplesManager.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.sdk.ui; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.eclipse.core.runtime.Path; import org.osgi.framework.Bundle; import com.amazonaws.eclipse.core.util.BundleUtils; public class SdkSamplesManager { public static List<SdkSample> getSamples() { File samplesPath = getSamplesBasedir(); File[] sampleDirectories = samplesPath.listFiles( new FileFilter() { /** * @see java.io.FileFilter#accept(java.io.File) */ @Override public boolean accept(File pathname) { return new File(pathname, "sample.properties").exists(); } }); List<SdkSample> samples = new ArrayList<>(); if (sampleDirectories == null || sampleDirectories.length == 0) { return samples; } for (File file : sampleDirectories) { try (FileInputStream inputStream = new FileInputStream(new File(file, "sample.properties"))) { Properties properties = new Properties(); properties.load(inputStream); samples.add(new SdkSample( properties.getProperty("name"), properties.getProperty("description"), new Path(file.getAbsolutePath()))); } catch (IOException e) { e.printStackTrace(); } } return samples; } private static File getSamplesBasedir() { Bundle bundle = JavaSdkPlugin.getDefault().getBundle(); File file = null; try { file = BundleUtils.getFileFromBundle(bundle, "samples"); } catch (IOException e) { throw new RuntimeException("Failed to find plugin bundle root.", e); } catch (URISyntaxException e) { throw new RuntimeException("Failed to find plugin sample folder", e); } return file; } }
7,311
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/wizard/NewAwsJavaProjectWizardPageOne.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.sdk.ui.wizard; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup; import java.util.ArrayList; import java.util.List; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.layout.GridDataFactory; 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.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Rectangle; 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.Group; import org.eclipse.swt.widgets.Label; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.ui.AccountSelectionComposite; import com.amazonaws.eclipse.core.ui.MavenConfigurationComposite; import com.amazonaws.eclipse.core.ui.ProjectNameComposite; import com.amazonaws.eclipse.sdk.ui.SdkSample; import com.amazonaws.eclipse.sdk.ui.SdkSamplesManager; import com.amazonaws.eclipse.sdk.ui.model.NewAwsJavaProjectWizardDataModel; /** * The first page of the AWS New Project Wizard. Allows the user to select: * <li> Account credentials * <li> A collection of samples to include in the new project */ class NewAwsJavaProjectWizardPageOne extends WizardPage { private static final String PAGE_NAME = NewAwsJavaProjectWizardPageOne.class.getName(); private final NewAwsJavaProjectWizardDataModel dataModel; private final DataBindingContext dataBindingContext; private final AggregateValidationStatus aggregateValidationStatus; // Composites modules in this page. private ProjectNameComposite projectNameComposite; private AccountSelectionComposite accountSelectionComposite; private MavenConfigurationComposite mavenConfigurationComposite; private SdkSamplesComposite sdkSamplesComposite; private ScrolledComposite scrolledComp; public NewAwsJavaProjectWizardPageOne(NewAwsJavaProjectWizardDataModel dataModel) { super(PAGE_NAME); setTitle("Create an AWS Java project"); setDescription("Create a new AWS Java project in the workspace"); this.dataModel = dataModel; this.dataBindingContext = new DataBindingContext(); this.aggregateValidationStatus = new AggregateValidationStatus( dataBindingContext, AggregateValidationStatus.MAX_SEVERITY); aggregateValidationStatus.addChangeListener(new IChangeListener() { @Override public void handleChange(ChangeEvent arg0) { populateValidationStatus(); } }); } private GridLayout initGridLayout(GridLayout layout, boolean margins) { layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); if ( margins ) { layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); } else { layout.marginWidth = 0; layout.marginHeight = 0; } return layout; } @Override public void createControl(final Composite parent) { initializeDialogUnits(parent); Composite composite = initCompositePanel(parent); createProjectNameComposite(composite); createMavenConfigurationComposite(composite); createAccountSelectionComposite(composite); createSamplesComposite(composite); setControl(scrolledComp); } private Composite initCompositePanel(Composite parent) { scrolledComp = new ScrolledComposite(parent, SWT.V_SCROLL); scrolledComp.setExpandHorizontal(true); scrolledComp.setExpandVertical(true); GridDataFactory.fillDefaults().grab(true, true).applyTo(scrolledComp); final Composite composite = new Composite(scrolledComp, SWT.NULL); composite.setFont(parent.getFont()); composite.setLayout(initGridLayout(new GridLayout(1, false), true)); composite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); scrolledComp.setContent(composite); scrolledComp.addControlListener(new ControlAdapter() { @Override public void controlResized(ControlEvent e) { Rectangle r = scrolledComp.getClientArea(); scrolledComp.setMinSize(composite.computeSize(r.width, SWT.DEFAULT)); } }); return composite; } protected void createProjectNameComposite(Composite composite) { projectNameComposite = new ProjectNameComposite( composite, dataBindingContext, dataModel.getProjectNameDataModel()); } protected void createSamplesComposite(Composite composite) { Group group = newGroup(composite, "AWS SDK for Java Samples"); sdkSamplesComposite = new SdkSamplesComposite(group, dataModel.getSdkSamples()); } protected void createAccountSelectionComposite(Composite composite) { Group group = newGroup(composite, "AWS Credentials"); accountSelectionComposite = new AccountSelectionComposite(group, SWT.NONE); accountSelectionComposite.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { dataModel.setAccountInfo(AwsToolkitCore.getDefault().getAccountManager().getAccountInfo( accountSelectionComposite.getSelectedAccountId())); } }); if (accountSelectionComposite.getSelectedAccountId() != null) dataModel.setAccountInfo(AwsToolkitCore.getDefault().getAccountManager().getAccountInfo( accountSelectionComposite.getSelectedAccountId())); } protected void createMavenConfigurationComposite(Composite composite) { Group group = newGroup(composite, "Maven configuration"); mavenConfigurationComposite = new MavenConfigurationComposite(group, dataBindingContext, dataModel.getMavenConfigurationDataModel()); } private void populateValidationStatus() { IStatus status = getValidationStatus(); if (status == null) return; if (status.getSeverity() == IStatus.OK) { this.setErrorMessage(null); super.setPageComplete(true); } else { setErrorMessage(status.getMessage()); super.setPageComplete(false); } } private IStatus getValidationStatus() { if (aggregateValidationStatus == null) return null; Object value = aggregateValidationStatus.getValue(); if (!(value instanceof IStatus)) return null; return (IStatus)value; } /** * Composite displaying the samples available in an SDK. */ private static class SdkSamplesComposite extends Composite { private final List<SdkSample> sdkSamples; private final List<Button> buttons = new ArrayList<>(); public SdkSamplesComposite(Composite parent, List<SdkSample> sdkSamples) { super(parent, SWT.NONE); this.sdkSamples = sdkSamples; createControls(); } private void createControls() { for ( Control c : this.getChildren()) { c.dispose(); } this.setLayout(new GridLayout()); List<SdkSample> totalSamples = SdkSamplesManager.getSamples(); for (SdkSample sample : totalSamples) { if (sample.getName() == null || sample.getDescription() == null) { // Sanity check - skip samples without names and descriptions. continue; } Button button = new Button(this, SWT.CHECK | SWT.WRAP); button.setText(sample.getName()); button.setData(sample); buttons.add(button); Label label = new Label(this, SWT.WRAP); label.setText(sample.getDescription()); GridData gridData = new GridData(SWT.BEGINNING, SWT.TOP, true, false); gridData.horizontalIndent = 25; label.setLayoutData(gridData); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { onButtonSelected(event); } }); } } private void onButtonSelected(SelectionEvent event) { Button sourceButton = (Button) event.getSource(); if (sourceButton.getSelection()) { this.sdkSamples.add((SdkSample)sourceButton.getData()); } else { this.sdkSamples.remove(sourceButton.getData()); } } } }
7,312
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/wizard/NewAwsJavaProjectWizard.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.sdk.ui.wizard; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import com.amazonaws.eclipse.core.AccountInfo; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.maven.MavenFactory; import com.amazonaws.eclipse.core.model.MavenConfigurationDataModel; import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin; import com.amazonaws.eclipse.core.plugin.AbstractAwsProjectWizard; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.eclipse.sdk.ui.FilenameFilters; import com.amazonaws.eclipse.sdk.ui.JavaSdkPlugin; import com.amazonaws.eclipse.sdk.ui.SdkSample; import com.amazonaws.eclipse.sdk.ui.model.NewAwsJavaProjectWizardDataModel; import static com.amazonaws.eclipse.core.util.JavaProjectUtils.setDefaultJreToProjectClasspath; /** * A Project Wizard for creating a new Java project configured to build against the * AWS SDK for Java. */ public class NewAwsJavaProjectWizard extends AbstractAwsProjectWizard { private static final String DEFAULT_GROUP_ID = "com.amazonaws"; private static final String DEFAULT_ARTIFACT_ID = "samples"; private static final String DEFAULT_VERSION = "1.0.0"; private static final String DEFAULT_PACKAGE_NAME = MavenFactory.assumePackageName(DEFAULT_GROUP_ID, DEFAULT_ARTIFACT_ID); private final NewAwsJavaProjectWizardDataModel dataModel = new NewAwsJavaProjectWizardDataModel(); private final String actionSource; private NewAwsJavaProjectWizardPageOne pageOne; private IProject project; /** * @see org.eclipse.jface.wizard.Wizard#addPages() */ @Override public void addPages() { if (pageOne == null) pageOne = new NewAwsJavaProjectWizardPageOne(dataModel); addPage(pageOne); } public NewAwsJavaProjectWizard() { this("Default"); } public NewAwsJavaProjectWizard(String actionSource) { super("New AWS Java Project"); this.actionSource = actionSource; initDataModel(); } @Override protected void initDataModel() { MavenConfigurationDataModel mavenDataModel = dataModel.getMavenConfigurationDataModel(); mavenDataModel.setGroupId(DEFAULT_GROUP_ID); mavenDataModel.setArtifactId(DEFAULT_ARTIFACT_ID); mavenDataModel.setVersion(DEFAULT_VERSION); mavenDataModel.setPackageName(DEFAULT_PACKAGE_NAME); dataModel.setActionSource(actionSource); } private void addSamplesToProject() throws CoreException, IOException { String packageName = dataModel.getMavenConfigurationDataModel().getPackageName(); AccountInfo accountInfo = dataModel.getAccountInfo(); List<SdkSample> samples = dataModel.getSdkSamples(); IPath srcPath = getSamplesRootFolder(packageName); if (!srcPath.toFile().exists()) { srcPath.toFile().mkdirs(); } AccountInfo selectedAccount = accountInfo; for (SdkSample sample : samples) { for (File sampleSourceFile : sample.getPath().toFile().listFiles(new FilenameFilters.JavaSourceFilenameFilter())) { String sampleContent = FileUtils.readFileToString(sampleSourceFile); if (selectedAccount != null) { sampleContent = updateSampleContentWithConfiguredProfile(sampleContent, selectedAccount, packageName); } IFileStore projectSourceFolderDestination = EFS.getLocalFileSystem().fromLocalFile( srcPath.append(sampleSourceFile.getName()).toFile()); try (PrintStream ps = new PrintStream( projectSourceFolderDestination.openOutputStream( EFS.OVERWRITE, null))) { ps.print(sampleContent); } } } } private Model getModel() { Model model = new Model(); model.setModelVersion(MavenFactory.getMavenModelVersion()); model.setGroupId(dataModel.getMavenConfigurationDataModel().getGroupId()); model.setArtifactId(dataModel.getMavenConfigurationDataModel().getArtifactId()); model.setVersion(dataModel.getMavenConfigurationDataModel().getVersion()); List<Dependency> dependencies = new ArrayList<>(); dependencies.add(MavenFactory.getLatestAwsSdkDependency("compile")); dependencies.add(MavenFactory.getAmazonKinesisClientDependency("1.2.1", "compile")); model.setDependencies(dependencies); return model; } // Return the package path where all the sample files are in. private IPath getSamplesRootFolder(String packageName) { IPath workspaceRoot = project.getWorkspace().getRoot().getRawLocation(); IPath srcPath = workspaceRoot.append(project.getFullPath()).append(MavenFactory.getMavenSourceFolder()) .append(packageName.replace('.', '/')); return srcPath; } private static String updateSampleContentWithConfiguredProfile(String sampleContent, final AccountInfo selectedAccount, final String packageName) { final String credFileLocation = AwsToolkitCore.getDefault().getPreferenceStore().getString( PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION); String paramString; if (AwsToolkitCore.getDefault().getPreferenceStore().isDefault( PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION)) { // Don't need to specify the file location paramString = String.format("\"%s\"", selectedAccount.getAccountName()); } else { paramString = String.format("\"%s\", \"%s\"", credFileLocation, selectedAccount.getAccountName()); } // Change the parameter of the ProfileCredentialsProvider sampleContent = sampleContent.replace( "new ProfileCredentialsProvider().getCredentials();", String.format("new ProfileCredentialsProvider(%s).getCredentials();", escapeBackSlashes(paramString))); // Remove the block of comment between "Before running the code" and "WARNING" String COMMNET_TO_REMOVE_REGEX = "(Before running the code:.*?)?Fill in your AWS access credentials.*?(?=WANRNING:)"; sampleContent = Pattern.compile(COMMNET_TO_REMOVE_REGEX, Pattern.DOTALL) // dot should match newline .matcher(sampleContent).replaceAll(""); // [default] ==> [selected-profile-name] sampleContent = sampleContent.replace( "[default]", String.format("[%s]", selectedAccount.getAccountName())); // (~/.aws/credentials) ==> (user-specified preference store value) sampleContent = sampleContent.replace( "(~/.aws/credentials)", String.format("(%s)", escapeBackSlashes(credFileLocation))); sampleContent = "package " + packageName + ";\n" + sampleContent; return sampleContent; } private static String escapeBackSlashes(String str) { return str.replace("\\", "\\\\"); } @Override protected IStatus doFinish(IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, 100); progress.setTaskName(getJobTitle()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); project = root.getProject(dataModel.getProjectNameDataModel().getProjectName()); Model mavenModel = getModel(); try { MavenFactory.createMavenProject(project, mavenModel, progress.newChild(50)); IJavaProject javaProject = JavaCore.create(project); setDefaultJreToProjectClasspath(javaProject, monitor); progress.worked(50); } catch (Exception e) { return JavaSdkPlugin.getDefault().logError( "Failed to create AWS Sample Maven Project.", e); } try { addSamplesToProject(); progress.worked(50); } catch (Exception e) { return JavaSdkPlugin.getDefault().logError( "Failed to add samples to AWS Sample Maven Project", e); } // Finally, refresh the project so that the new files show up try { project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { return JavaSdkPlugin.getDefault().logWarning( "Unable to refresh the created project.", e); } return Status.OK_STATUS; } @Override protected void afterExecution(IStatus status) { super.afterExecution(status); if (status.isOK()) { dataModel.actionSucceeded(); } else { dataModel.actionFailed(); } dataModel.setActionExecutionTimeMillis(Long.valueOf(getActionExecutionTimeMillis())); dataModel.publishMetrics(); } @Override protected String getJobTitle() { return "Creating AWS Java Project"; } @Override public boolean performCancel() { dataModel.actionCanceled(); dataModel.publishMetrics(); return super.performCancel(); } @Override protected AbstractAwsPlugin getPlugin() { return JavaSdkPlugin.getDefault(); } }
7,313
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/menu/NewAwsJavaProjectHandler.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.sdk.ui.menu; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import com.amazonaws.eclipse.sdk.ui.wizard.NewAwsJavaProjectWizard; public class NewAwsJavaProjectHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { NewAwsJavaProjectWizard newWizard = new NewAwsJavaProjectWizard("Menu"); newWizard.init(PlatformUI.getWorkbench(), null); WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard); return dialog.open(); } }
7,314
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/model/NewAwsJavaProjectWizardDataModel.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.sdk.ui.model; import java.util.ArrayList; import java.util.List; import com.amazonaws.eclipse.core.AccountInfo; import com.amazonaws.eclipse.core.model.MavenConfigurationDataModel; import com.amazonaws.eclipse.core.model.ProjectNameDataModel; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.core.telemetry.MetricsDataModel; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.eclipse.sdk.ui.SdkSample; public class NewAwsJavaProjectWizardDataModel { private String actionSource; private final ProjectNameDataModel projectNameDataModel = new ProjectNameDataModel(); private final MavenConfigurationDataModel mavenConfigurationDataModel = new MavenConfigurationDataModel(); private AccountInfo accountInfo; private final List<SdkSample> sdkSamples = new ArrayList<>(); private String endResult; private Long actionExecutionTimeMillis; public AccountInfo getAccountInfo() { return accountInfo; } public void setAccountInfo(AccountInfo accountInfo) { this.accountInfo = accountInfo; } public List<SdkSample> getSdkSamples() { return sdkSamples; } public MavenConfigurationDataModel getMavenConfigurationDataModel() { return mavenConfigurationDataModel; } public ProjectNameDataModel getProjectNameDataModel() { return projectNameDataModel; } public String getActionSource() { return actionSource; } public void setActionSource(String actionSource) { this.actionSource = actionSource; } public void actionFailed() { endResult = AwsAction.FAILED; } public void actionSucceeded() { endResult = AwsAction.SUCCEEDED; } public void actionCanceled() { endResult = AwsAction.CANCELED; } public void publishMetrics() { MetricsDataModel metricsDataModel = new MetricsDataModel(AwsToolkitMetricType.AWS_NEW_JAVA_PROJECT_WIZARD); metricsDataModel.addAttribute("ActionSource", actionSource); for (SdkSample sample: sdkSamples) { metricsDataModel.addBooleanMetric(sample.getName(), true); } metricsDataModel.addAttribute(AwsAction.END_RESULT, endResult); if (actionExecutionTimeMillis != null) { metricsDataModel.addMetric("ExecutionTimeMillis", (double) actionExecutionTimeMillis); } metricsDataModel.publishEvent(); } public void setActionExecutionTimeMillis(Long actionExecutionTimeMillis) { this.actionExecutionTimeMillis = actionExecutionTimeMillis; } }
7,315
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/CodeCommitConstants.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.codecommit; public class CodeCommitConstants { public static final String CODECOMMIT_SERVICE_NAME = "codecommit.amazonaws.com"; }
7,316
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/CodeCommitAnalytics.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.ToolkitAnalyticsManager; import com.amazonaws.eclipse.core.telemetry.ToolkitEvent.ToolkitEventBuilder; public class CodeCommitAnalytics { private static final ToolkitAnalyticsManager ANALYTICS = AwsToolkitCore.getDefault().getAnalyticsManager(); // Create Repository Event private static final String EVENT_CREATE_REPOSITORY = "codecommit_createRepo"; // Clone Repository Event private static final String EVENT_CLONE_REPOSITORY = "codecommit_cloneRepo"; // Delete Repository Event private static final String EVENT_DELETE_REPOSITORY = "codecommit_deleteRepo"; // Open Repository Editor private static final String EVENT_OPEN_REPOSITORY_EDITOR = "codecommit_openEditor"; // Attribute private static final String ATTR_NAME_END_RESULT = "result"; public static void trackCreateRepository(EventResult result) { publishEventWithAttributes(EVENT_CREATE_REPOSITORY, ATTR_NAME_END_RESULT, result.getResultText()); } public static void trackCloneRepository(EventResult result) { publishEventWithAttributes(EVENT_CLONE_REPOSITORY, ATTR_NAME_END_RESULT, result.getResultText()); } public static void trackDeleteRepository(EventResult result) { publishEventWithAttributes(EVENT_DELETE_REPOSITORY, ATTR_NAME_END_RESULT, result.getResultText()); } public static void trackOpenRepositoryEditor(EventResult result) { publishEventWithAttributes(EVENT_OPEN_REPOSITORY_EDITOR, ATTR_NAME_END_RESULT, result.getResultText()); } private static void publishEventWithAttributes(String eventType, String... attributes) { ToolkitEventBuilder builder = ANALYTICS.eventBuilder().setEventType(eventType); for (int i = 0; i < attributes.length; i += 2) { builder.addAttribute(attributes[i], attributes[i + 1]); } ANALYTICS.publishEvent(builder.build()); } public static enum EventResult { SUCCEEDED("Succeeded"), FAILED("Failed"), CANCELED("Canceled") ; private final String resultText; private EventResult(String resultText) { this.resultText = resultText; } public String getResultText() { return resultText; } } }
7,317
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/CodeCommitUtil.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit; import java.text.SimpleDateFormat; import java.util.Date; public class CodeCommitUtil { public static String codeCommitTimeToHumanReadible(String time) { String[] token = time.split(" "); if (token.length != 2) return null; long epochTime = Long.parseLong(token[0]); return new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date (epochTime*1000)); } /** * Return value if it is not null, otherwise, return empty string. */ public static String nonNullString(String value) { return value == null ? "" : value; } }
7,318
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/CodeCommitPlugin.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.widgets.Display; import org.osgi.framework.BundleContext; import com.amazonaws.eclipse.codecommit.credentials.GitCredential; import com.amazonaws.eclipse.codecommit.credentials.GitCredentialsManager; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.services.codecommit.AWSCodeCommit; import com.amazonaws.util.StringUtils; /** * The activator class controls the plug-in life cycle */ public class CodeCommitPlugin extends AbstractAwsPlugin { // The plug-in ID public static final String PLUGIN_ID = "com.amazonaws.eclipse.codecommit"; //$NON-NLS-1$ // The icon IDs public static final String IMG_SERVICE = "codecommit-service"; public static final String IMG_REPOSITORY = "codecommit-repo"; // The shared instance private static CodeCommitPlugin 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; GitCredentialsManager.init(); } /* * (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 CodeCommitPlugin getDefault() { return plugin; } @Override protected ImageRegistry createImageRegistry() { ImageRegistry imageRegistry = new ImageRegistry(Display.getCurrent()); imageRegistry.put(IMG_SERVICE, ImageDescriptor.createFromFile(getClass(), "/icons/codecommit-service.png")); imageRegistry.put(IMG_REPOSITORY, ImageDescriptor.createFromFile(getClass(), "/icons/codecommit-repo.png")); return imageRegistry; } /** * Returns a CodeCommit client for the current account and region. */ public static AWSCodeCommit getCurrentCodeCommitClient() { String endpoint = RegionUtils.getCurrentRegion().getServiceEndpoint(ServiceAbbreviations.CODECOMMIT); return AwsToolkitCore.getClientFactory().getCodeCommitClientByEndpoint(endpoint); } /** * Utility method that returns whether the Git credentials are configured for the current profile. */ public static boolean currentProfileGitCredentialsConfigured() { String profile = AwsToolkitCore.getDefault().getAccountInfo().getAccountName(); GitCredential credential = GitCredentialsManager.getGitCredential(profile); return !StringUtils.isNullOrEmpty(credential.getUsername()) && !StringUtils.isNullOrEmpty(credential.getPassword()); } }
7,319
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/preferences/PreferenceInitializer.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.preferences; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; import com.amazonaws.eclipse.codecommit.CodeCommitPlugin; public class PreferenceInitializer extends AbstractPreferenceInitializer{ @Override public void initializeDefaultPreferences() { IPreferenceStore store = CodeCommitPlugin.getDefault().getPreferenceStore(); store.setDefault( PreferenceConstants.GIT_CREDENTIALS_FILE_PREFERENCE_NAME, PreferenceConstants.DEFAULT_GIT_CREDENTIALS_FILE ); } }
7,320
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/preferences/CodeCommitPreferencePage.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.preferences; import static com.amazonaws.eclipse.codecommit.model.CodeCommitPreferencePageDataModel.P_PROFILE; import java.util.Map; import java.util.Map.Entry; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.preference.FileFieldEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import com.amazonaws.eclipse.codecommit.CodeCommitPlugin; import com.amazonaws.eclipse.codecommit.credentials.GitCredential; import com.amazonaws.eclipse.codecommit.credentials.GitCredentialsManager; import com.amazonaws.eclipse.codecommit.model.CodeCommitPreferencePageDataModel; import com.amazonaws.eclipse.codecommit.widgets.GitCredentialsComposite; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.ui.preferences.AwsToolkitPreferencePage; import com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory; import com.amazonaws.eclipse.core.validator.NoopValidator; public class CodeCommitPreferencePage extends AwsToolkitPreferencePage implements IWorkbenchPreferencePage { public static final String ID = "com.amazonaws.eclipse.codecommit.preferences.CodeCommitPreferencePage"; private final CodeCommitPreferencePageDataModel dataModel = new CodeCommitPreferencePageDataModel(); private final DataBindingContext dataBindingContext = new DataBindingContext(); private Combo profileCombo; private GitCredentialsComposite gitCredentialsComposite; private FileFieldEditor gitCredentailsFileLocation; public CodeCommitPreferencePage() { super("AWS CodeCommit Preferences"); } @Override public void init(IWorkbench workbench) { setPreferenceStore(CodeCommitPlugin.getDefault().getPreferenceStore()); initDataModel(); } @Override protected Control createContents(Composite parent) { final Composite composite = new Composite(parent, SWT.LEFT); composite.setLayout(new GridLayout()); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); createGitCredentialsSection(composite); createGitCredentialsFileSection(composite); return composite; } private void createGitCredentialsSection(Composite composite) { Group gitCredentialsGroup = newGroup("Configure Git Credentials:", composite); gitCredentialsGroup.setLayout(new GridLayout(1, false)); createProfileComboBoxSection(gitCredentialsGroup); gitCredentialsComposite = new GitCredentialsComposite( gitCredentialsGroup, dataBindingContext, dataModel.getGitCredentialsDataModel(), new NoopValidator(), new NoopValidator()); } private void createProfileComboBoxSection(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); WizardWidgetFactory.newLabel(composite, "Profile: "); profileCombo = WizardWidgetFactory.newCombo(composite); Map<String, GitCredential> credentials = GitCredentialsManager.getGitCredentials(); for (Entry<String, GitCredential> entry : credentials.entrySet()) { profileCombo.add(entry.getKey()); profileCombo.setData(entry.getKey(), entry.getValue()); } String defaultAccountName = dataModel.getProfile(); profileCombo.select(profileCombo.indexOf(defaultAccountName)); dataBindingContext.bindValue(SWTObservables.observeText(profileCombo), PojoObservables.observeValue(dataModel, P_PROFILE)); profileCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { populateGitCredentialsComposite(); } }); } private void createGitCredentialsFileSection(Composite composite) { Group gitCredentialsFileGroup = newGroup("Configure Git Credentials File Path:", composite); gitCredentialsFileGroup.setLayout(new GridLayout(1, false)); gitCredentailsFileLocation = new FileFieldEditor( PreferenceConstants.GIT_CREDENTIALS_FILE_PREFERENCE_NAME, "Git Credentials file:", true, gitCredentialsFileGroup); gitCredentailsFileLocation.setPage(this); gitCredentailsFileLocation.setPreferenceStore(getPreferenceStore()); gitCredentailsFileLocation.load(); } private void initDataModel() { String profileName = AwsToolkitCore.getDefault().getAccountInfo().getAccountName(); GitCredential credential = GitCredentialsManager.getGitCredential(profileName); dataModel.setProfile(profileName); dataModel.getGitCredentialsDataModel().setUsername(credential.getUsername()); dataModel.getGitCredentialsDataModel().setPassword(credential.getPassword()); } private void populateGitCredentialsComposite() { String profile = dataModel.getProfile(); GitCredential selectedGitCredential = GitCredentialsManager.getGitCredential(profile); if (selectedGitCredential != null) { gitCredentialsComposite.populateGitCredential( selectedGitCredential.getUsername(), selectedGitCredential.getPassword()); } else { gitCredentialsComposite.populateGitCredential( "", ""); } String userAccount = AwsToolkitCore.getDefault().getAccountManager().getAllAccountIds().get(profile); dataModel.getGitCredentialsDataModel().setUserAccount(userAccount); dataModel.getGitCredentialsDataModel().setRegionId(RegionUtils.getCurrentRegion().getId()); } @Override protected void performDefaults() { if (gitCredentailsFileLocation != null) { gitCredentailsFileLocation.loadDefault(); } super.performDefaults(); } @Override public boolean performOk() { onApplyButton(); return super.performOk(); } @Override public void performApply() { onApplyButton(); super.performApply(); } private void onApplyButton() { String previousLocation = getPreferenceStore().getString(PreferenceConstants.GIT_CREDENTIALS_FILE_PREFERENCE_NAME); String currentLocation = previousLocation; if (gitCredentailsFileLocation != null) { gitCredentailsFileLocation.store(); currentLocation = gitCredentailsFileLocation.getStringValue(); } if (previousLocation.equalsIgnoreCase(currentLocation)) { GitCredentialsManager.getGitCredentials().put(dataModel.getProfile(), new GitCredential(dataModel.getGitCredentialsDataModel().getUsername(), dataModel.getGitCredentialsDataModel().getPassword())); GitCredentialsManager.saveGitCredentials(); } else { GitCredentialsManager.loadGitCredentials(); populateGitCredentialsComposite(); } } }
7,321
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/preferences/PreferenceConstants.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.preferences; import java.io.File; /** * Preference constant values for CodeCommit plugin. */ public class PreferenceConstants { public static final String GIT_CREDENTIALS_FILE_PREFERENCE_NAME = "com.amazonaws.eclipse.codecommit.preference.GitCredentialsFile"; public static final String DEFAULT_GIT_CREDENTIALS_FILE; static { DEFAULT_GIT_CREDENTIALS_FILE = new File( System.getProperty("user.home") + File.separator + ".aws" + File.separator + "gitCredentials") .getAbsolutePath(); } }
7,322
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/wizard/CloneRepositoryWizard.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.wizard; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.net.URISyntaxException; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jgit.transport.URIish; import org.eclipse.ui.IImportWizard; import org.eclipse.ui.IWorkbench; import com.amazonaws.eclipse.codecommit.CodeCommitAnalytics; import com.amazonaws.eclipse.codecommit.CodeCommitPlugin; import com.amazonaws.eclipse.codecommit.CodeCommitAnalytics.EventResult; import com.amazonaws.eclipse.codecommit.credentials.GitCredential; import com.amazonaws.eclipse.codecommit.credentials.GitCredentialsManager; import com.amazonaws.eclipse.codecommit.pages.GitCredentialsConfigurationPage; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.egit.GitRepositoryInfo; import com.amazonaws.eclipse.core.egit.RepositorySelection; import com.amazonaws.eclipse.core.egit.UIText; import com.amazonaws.eclipse.core.egit.jobs.CloneGitRepositoryJob; import com.amazonaws.eclipse.core.egit.jobs.ImportProjectJob; import com.amazonaws.eclipse.core.egit.ui.CloneDestinationPage; import com.amazonaws.eclipse.core.egit.ui.SourceBranchPage; import com.amazonaws.eclipse.core.exceptions.AwsActionException; import com.amazonaws.eclipse.core.model.GitCredentialsDataModel; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.core.util.WorkbenchUtils; import com.amazonaws.services.codecommit.AWSCodeCommit; import com.amazonaws.services.codecommit.model.GetRepositoryRequest; import com.amazonaws.services.codecommit.model.RepositoryMetadata; public class CloneRepositoryWizard extends Wizard implements IImportWizard { protected IWorkbench workbench; private final AWSCodeCommit client; private final String repositoryName; private final String currentProfile; private final GitCredentialsDataModel dataModel = new GitCredentialsDataModel(); protected GitCredentialsConfigurationPage credentialConfigPage; // a page for repository branch selection protected SourceBranchPage sourceBranchPage; // a page for selection of the clone destination protected CloneDestinationPage cloneDestinationPage; private GitRepositoryInfo gitRepositoryInfo; public CloneRepositoryWizard(String accountId, String regionId, String repositoryName) throws URISyntaxException { super(); if (accountId == null) { accountId = AwsToolkitCore.getDefault().getCurrentAccountId(); } if (regionId == null) { regionId = RegionUtils.getCurrentRegion().getId(); } this.client = AwsToolkitCore.getClientFactory(accountId).getCodeCommitClientByRegion(regionId); this.repositoryName = repositoryName; this.currentProfile = AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(accountId).getAccountName(); setWindowTitle("Clone AWS CodeCommit Repository"); setNeedsProgressMonitor(true); GitCredential credential = GitCredentialsManager.getGitCredential(currentProfile); if (credential != null) { dataModel.setUsername(credential.getUsername()); dataModel.setPassword(credential.getPassword()); } dataModel.setUserAccount(accountId); dataModel.setRegionId(regionId); } @Override public void init(IWorkbench workbench, IStructuredSelection selection) { this.workbench = workbench; } @Override public final void addPages() { if (!CodeCommitPlugin.currentProfileGitCredentialsConfigured()) { credentialConfigPage = new GitCredentialsConfigurationPage(dataModel); addPage(credentialConfigPage); } sourceBranchPage = createSourceBranchPage(); cloneDestinationPage = createCloneDestinationPage(); addPage(sourceBranchPage); addPage(cloneDestinationPage); } @Override public boolean performFinish() { try { final File destinationFile = cloneDestinationPage.getDestinationFile(); getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.subTask("Cloning repository..."); GitCredentialsManager.getGitCredentials().put(currentProfile, new GitCredential(dataModel.getUsername(), dataModel.getPassword())); GitCredentialsManager.saveGitCredentials(); try { new CloneGitRepositoryJob(CloneRepositoryWizard.this, sourceBranchPage, cloneDestinationPage, getTheGitRepositoryInfo()) .execute(monitor); } catch (URISyntaxException e) { throw new InvocationTargetException(e); } monitor.subTask("Importing project..."); IFile fileToOpen = new ImportProjectJob(repositoryName, destinationFile) .execute(monitor); if (fileToOpen != null) { WorkbenchUtils.selectAndReveal(fileToOpen, workbench); // show in explorer WorkbenchUtils.openFileInEditor(fileToOpen, workbench); // show in editor } monitor.done(); } }); } catch (InvocationTargetException e) { CodeCommitAnalytics.trackCloneRepository(EventResult.FAILED); CodeCommitPlugin.getDefault().reportException("Failed to clone git repository.", new AwsActionException(AwsToolkitMetricType.EXPLORER_CODECOMMIT_CLONE_REPO.getName(), e.getMessage(), e)); return false; } catch (InterruptedException e) { CodeCommitAnalytics.trackCloneRepository(EventResult.CANCELED); CodeCommitPlugin.getDefault().reportException( UIText.GitCreateProjectViaWizardWizard_AbortedMessage, e); return false; } CodeCommitAnalytics.trackCloneRepository(EventResult.SUCCEEDED); return true; } @Override public boolean performCancel() { CodeCommitAnalytics.trackCloneRepository(EventResult.CANCELED); return super.performCancel(); } private SourceBranchPage createSourceBranchPage() { return new SourceBranchPage() { @Override public void setVisible(boolean visible) { if (visible) { try { setSelection(getRepositorySelection()); setCredentials(getTheGitRepositoryInfo().getCredentials()); } catch (URISyntaxException e) { throw new RuntimeException(e); } } super.setVisible(visible); } }; } private CloneDestinationPage createCloneDestinationPage() { return new CloneDestinationPage() { @Override public void setVisible(boolean visible) { if (visible) setSelection(getRepositorySelection(), sourceBranchPage.getAvailableBranches(), sourceBranchPage.getSelectedBranches(), sourceBranchPage.getHEAD()); super.setVisible(visible); } }; } /** * @return the repository specified in the data model. */ private RepositorySelection getRepositorySelection() { try { return new RepositorySelection(new URIish(getTheGitRepositoryInfo().getCloneUri()), null); } catch (URISyntaxException e) { CodeCommitPlugin.getDefault().reportException( UIText.GitImportWizard_errorParsingURI, e); return null; } catch (Exception e) { CodeCommitPlugin.getDefault().reportException(e.getMessage(), e); return null; } } private GitRepositoryInfo getTheGitRepositoryInfo() throws URISyntaxException { if (gitRepositoryInfo == null) { RepositoryMetadata metadata = client.getRepository( new GetRepositoryRequest() .withRepositoryName(repositoryName)) .getRepositoryMetadata(); this.gitRepositoryInfo = createGitRepositoryInfo( metadata.getCloneUrlHttp(), metadata.getRepositoryName(), dataModel.getUsername(), dataModel.getPassword()); } return this.gitRepositoryInfo; } private static GitRepositoryInfo createGitRepositoryInfo(String httpUrl, String repoName, String username, String password) throws URISyntaxException { GitRepositoryInfo info = new GitRepositoryInfo(httpUrl); info.setRepositoryName(repoName); info.setShouldSaveCredentialsInSecureStore(true); info.setCredentials(username, password); return info; } }
7,323
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/explorer/CodeCommitActionProvider.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.explorer; import java.util.ArrayList; import java.util.Iterator; 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.core.runtime.jobs.Job; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.TitleAreaDialog; 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.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.navigator.CommonActionProvider; import com.amazonaws.eclipse.codecommit.CodeCommitPlugin; import com.amazonaws.eclipse.codecommit.wizard.CloneRepositoryWizard; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.exceptions.AwsActionException; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.core.ui.DeleteResourceConfirmationDialog; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.eclipse.explorer.ContentProviderRegistry; import com.amazonaws.services.codecommit.AWSCodeCommit; import com.amazonaws.services.codecommit.model.CreateRepositoryRequest; import com.amazonaws.services.codecommit.model.DeleteRepositoryRequest; import com.amazonaws.services.codecommit.model.RepositoryNameIdPair; import com.amazonaws.util.StringUtils; public class CodeCommitActionProvider extends CommonActionProvider { @Override public void fillContextMenu(IMenuManager menu) { StructuredSelection selection = (StructuredSelection)getActionSite().getStructuredViewer().getSelection(); @SuppressWarnings("rawtypes") Iterator iterator = selection.iterator(); boolean rootElementSelected = false; List<RepositoryNameIdPair> repositories = new ArrayList<>(); while ( iterator.hasNext() ) { Object obj = iterator.next(); if ( obj instanceof RepositoryNameIdPair ) { repositories.add((RepositoryNameIdPair) obj); } if ( obj instanceof CodeCommitRootElement ) { rootElementSelected = true; } } if ( rootElementSelected && repositories.isEmpty()) { menu.add(new CreateRepositoryAction()); } else if ( !rootElementSelected && !repositories.isEmpty() ) { if (repositories.size() == 1) { menu.add(new CloneRepositoryAction(repositories.get(0))); menu.add(new OpenRepositoryEditorAction(repositories.get(0))); menu.add(new DeleteRepositoryAction(repositories.get(0))); } } } private static class CreateRepositoryAction extends AwsAction { public CreateRepositoryAction() { super(AwsToolkitMetricType.EXPLORER_CODECOMMIT_CREATE_REPO); this.setText("Create Repository"); this.setToolTipText("Create a secure repository to store and share your code."); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD)); } @Override protected void doRun() { NewRepositoryDialog dialog = new NewRepositoryDialog(Display.getDefault().getActiveShell()); if (Window.OK == dialog.open()) { AWSCodeCommit client = CodeCommitPlugin.getCurrentCodeCommitClient(); try { client.createRepository(new CreateRepositoryRequest() .withRepositoryName(dialog.getRepositoryName()) .withRepositoryDescription(dialog.getRepositoryDescription())); ContentProviderRegistry.refreshAllContentProviders(); actionSucceeded(); } catch (Exception e) { actionFailed(); CodeCommitPlugin.getDefault().reportException("Failed to create repository!", new AwsActionException(AwsToolkitMetricType.EXPLORER_CODECOMMIT_CREATE_REPO.getName(), e.getMessage(), e)); } } else { actionCanceled(); } actionFinished(); } private static class NewRepositoryDialog extends TitleAreaDialog { public NewRepositoryDialog(Shell parentShell) { super(parentShell); } private Text repositoryNameText; private Text repositoryDescriptionText; private String repositoryName; private String repositoryDescription; @Override public void create() { super.create(); setTitle("Create Repository"); setMessage("Create a secure repository to store and share your code. " + "Begin by typing a repository name and a description for your repository. " + "Repository names are included in the URLs for that repository.", IMessageProvider.INFORMATION); getButton(IDialogConstants.OK_ID).setEnabled(false); } @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout layout = new GridLayout(2, false); container.setLayout(layout); createRepositoryNameSection(container); createRepositoryDescriptionSection(container); return area; } private void createRepositoryNameSection(Composite container) { Label repositoryNameLabel = new Label(container, SWT.NONE); repositoryNameLabel.setText("Repository Name*: "); GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = SWT.FILL; repositoryNameText = new Text(container, SWT.BORDER); repositoryNameText.setMessage("100 character limit"); repositoryNameText.setLayoutData(gridData); repositoryNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent event) { String inputRepositoryName = repositoryNameText.getText(); getButton(IDialogConstants.OK_ID).setEnabled(!StringUtils.isNullOrEmpty(inputRepositoryName)); } }); } private void createRepositoryDescriptionSection(Composite container) { Label repositoryDescriptionLabel = new Label(container, SWT.NONE); repositoryDescriptionLabel.setText("Repository Description: "); GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = SWT.FILL; repositoryDescriptionText = new Text(container, SWT.BORDER); repositoryDescriptionText.setMessage("1000 character limit"); repositoryDescriptionText.setLayoutData(gridData); } @Override protected boolean isResizable() { return true; } private void saveInput() { repositoryName = repositoryNameText.getText(); repositoryDescription = repositoryDescriptionText.getText(); } @Override protected void okPressed() { saveInput(); super.okPressed(); } public String getRepositoryName() { return repositoryName; } public String getRepositoryDescription() { return repositoryDescription; } } } public static class CloneRepositoryAction extends AwsAction { private final String accountId; private final String regionId; private final String repositoryName; public CloneRepositoryAction(RepositoryNameIdPair repository) { this(null, null, repository.getRepositoryName()); } public CloneRepositoryAction(RepositoryEditorInput repositoryEditorInput) { this(repositoryEditorInput.getAccountId(), repositoryEditorInput.getRegionId(), repositoryEditorInput.getRepository().getRepositoryName()); } private CloneRepositoryAction(String accountId, String regionId, String repositoryName) { super(AwsToolkitMetricType.EXPLORER_CODECOMMIT_CLONE_REPO); this.accountId = accountId; this.regionId = regionId; this.repositoryName = repositoryName; this.setText("Clone Repository"); this.setToolTipText("Create a secure repository to store and share your code."); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_EXPORT)); } @Override protected void doRun() { try { WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), new CloneRepositoryWizard(accountId, regionId, repositoryName)); dialog.open(); actionSucceeded(); } catch (Exception e) { CodeCommitPlugin.getDefault().reportException("Failed to clone CodeCommit repository!", new AwsActionException(AwsToolkitMetricType.EXPLORER_CODECOMMIT_CLONE_REPO.getName(), e.getMessage(), e)); actionFailed(); } finally { actionFinished(); } } } private static class DeleteRepositoryAction extends AwsAction { private final RepositoryNameIdPair repository; public DeleteRepositoryAction(RepositoryNameIdPair repository) { super(AwsToolkitMetricType.EXPLORER_CODECOMMIT_DELETE_REPO); this.repository = repository; this.setText("Delete Repository"); this.setToolTipText("Deleting this repository from AWS CodeCommit will remove the remote repository for all users."); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE)); } @Override public void doRun() { Dialog dialog = new DeleteResourceConfirmationDialog(Display.getDefault().getActiveShell(), repository.getRepositoryName(), "repository"); if (dialog.open() != Window.OK) { actionCanceled(); actionFinished(); return; } Job deleteRepositoriesJob = new Job("Deleting Repository...") { @Override protected IStatus run(IProgressMonitor monitor) { AWSCodeCommit codecommit = AwsToolkitCore.getClientFactory().getCodeCommitClient(); IStatus status = Status.OK_STATUS; try { codecommit.deleteRepository(new DeleteRepositoryRequest().withRepositoryName(repository.getRepositoryName())); actionSucceeded(); } catch (Exception e) { status = new Status(IStatus.ERROR, CodeCommitPlugin.getDefault().getPluginId(), e.getMessage(), e); actionFailed(); } finally { actionFinished(); } ContentProviderRegistry.refreshAllContentProviders(); return status; } }; deleteRepositoriesJob.schedule(); } } public static class OpenRepositoryEditorAction extends AwsAction { private final RepositoryNameIdPair repository; public OpenRepositoryEditorAction(RepositoryNameIdPair repository) { super(AwsToolkitMetricType.EXPLORER_CODECOMMIT_OPEN_REPO_EDITOR); this.repository = repository; this.setText("Open in CodeCommit Repository Editor"); } @Override public void doRun() { String endpoint = RegionUtils.getCurrentRegion().getServiceEndpoint(ServiceAbbreviations.CODECOMMIT); String accountId = AwsToolkitCore.getDefault().getCurrentAccountId(); String regionId = RegionUtils.getCurrentRegion().getId(); final IEditorInput input = new RepositoryEditorInput(repository, endpoint, accountId, regionId); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); activeWindow.getActivePage().openEditor(input, RepositoryEditor.ID); actionSucceeded(); } catch (PartInitException e) { actionFailed(); CodeCommitPlugin.getDefault().logError("Unable to open the AWS CodeCommit Repository Editor.", e); } finally { actionFinished(); } } }); } } }
7,324
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/explorer/RepositoryEditor.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.explorer; import static com.amazonaws.eclipse.codecommit.CodeCommitUtil.nonNullString; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ComboViewer; 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.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.part.EditorPart; import com.amazonaws.eclipse.codecommit.CodeCommitPlugin; import com.amazonaws.eclipse.codecommit.CodeCommitUtil; import com.amazonaws.eclipse.codecommit.explorer.CodeCommitActionProvider.CloneRepositoryAction; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.services.codecommit.AWSCodeCommit; import com.amazonaws.services.codecommit.model.Commit; import com.amazonaws.services.codecommit.model.GetBranchRequest; import com.amazonaws.services.codecommit.model.GetCommitRequest; import com.amazonaws.services.codecommit.model.GetRepositoryRequest; import com.amazonaws.services.codecommit.model.ListBranchesRequest; import com.amazonaws.services.codecommit.model.RepositoryMetadata; import com.amazonaws.util.StringUtils; public class RepositoryEditor extends EditorPart { public final static String ID = "com.amazonaws.eclipse.codecommit.explorer.RepositoryEditor"; private static final int DEFAUT_COMMIT_HISTORY_COUNT = 10; private RepositoryEditorInput repositoryEditorInput; private AWSCodeCommit client; private Text lastModifiedDateText; private Text repositoryDescriptionText; private Text cloneUrlHttpText; private Text cloneUrlSSHText; private Combo branchCombo; private TreeViewer viewer; @Override public void doSave(IProgressMonitor monitor) {} @Override public void doSaveAs() {} @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); repositoryEditorInput = (RepositoryEditorInput) input; client = AwsToolkitCore.getClientFactory(repositoryEditorInput.getAccountId()) .getCodeCommitClientByEndpoint(repositoryEditorInput.getRegionEndpoint()); setPartName(input.getName()); } @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } @Override public void createPartControl(Composite parent) { FormToolkit toolkit = new FormToolkit(Display.getDefault()); ScrolledForm form = new ScrolledForm(parent, SWT.V_SCROLL); toolkit.decorateFormHeading(form.getForm()); form.setExpandHorizontal(true); form.setExpandVertical(true); form.setBackground(toolkit.getColors().getBackground()); form.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); form.setFont(JFaceResources.getHeaderFont()); form.setText(repositoryEditorInput.getName()); form.setImage(CodeCommitPlugin.getDefault().getImageRegistry().get(CodeCommitPlugin.IMG_REPOSITORY)); form.getBody().setLayout(new GridLayout()); createRepositorySummary(form.getBody(), toolkit); createCommitHistory(form.getBody(), toolkit); form.getToolBarManager().add(new RefreshAction()); form.getToolBarManager().update(true); } private void createRepositorySummary(Composite parent, FormToolkit toolkit) { final String repositoryName = repositoryEditorInput.getRepository().getRepositoryName(); final Composite composite = toolkit.createComposite(parent); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); toolkit.createLabel(composite, "Last Modified Date: "); lastModifiedDateText = toolkit.createText(composite, "", SWT.READ_ONLY); lastModifiedDateText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); toolkit.createLabel(composite, "Repository Description: "); repositoryDescriptionText = toolkit.createText(composite, "", SWT.READ_ONLY | SWT.H_SCROLL | SWT.FLAT); repositoryDescriptionText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); toolkit.createLabel(composite, "Clone URL Https: "); cloneUrlHttpText = toolkit.createText(composite, "", SWT.READ_ONLY); cloneUrlHttpText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); toolkit.createLabel(composite, "Clone URL SSH: "); cloneUrlSSHText = toolkit.createText(composite, "", SWT.READ_ONLY); cloneUrlSSHText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); Button checkoutButton = toolkit.createButton(composite, "Check out", SWT.PUSH); checkoutButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new CloneRepositoryAction(repositoryEditorInput).run(); } }); new LoadSummaryDataThread().start(); } private void createCommitHistory(Composite parent, FormToolkit toolkit) { Composite commitHistoryComposite = toolkit.createComposite(parent); commitHistoryComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); commitHistoryComposite.setLayout(new GridLayout()); Composite headerComposite = toolkit.createComposite(commitHistoryComposite); headerComposite.setLayout(new GridLayout(2, true)); headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); Label label = toolkit.createLabel(headerComposite, "Commit History for Branch:"); label.setFont(JFaceResources.getHeaderFont()); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); ComboViewer branchComboViewer = new ComboViewer(headerComposite, SWT.READ_ONLY | SWT.DROP_DOWN); branchCombo = branchComboViewer.getCombo(); branchCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); branchCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onBranchSelected(); } }); Composite composite = toolkit.createComposite(commitHistoryComposite); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); TreeColumnLayout tableColumnLayout = new TreeColumnLayout(); composite.setLayout(tableColumnLayout); CommitContentProvider contentProvider = new CommitContentProvider(); CommitLabelProvider labelProvider = new CommitLabelProvider(); viewer = new TreeViewer(composite, SWT.BORDER | SWT.MULTI); viewer.getTree().setLinesVisible(true); viewer.getTree().setHeaderVisible(true); viewer.setLabelProvider(labelProvider); viewer.setContentProvider(contentProvider); createColumns(tableColumnLayout, viewer.getTree()); viewer.setInput(new Object()); new LoadBranchesThread().start(); } private void createColumns(TreeColumnLayout columnLayout, Tree tree) { createColumn(tree, columnLayout, "Commit ID"); createColumn(tree, columnLayout, "Message"); createColumn(tree, columnLayout, "Committer"); createColumn(tree, columnLayout, "Date"); } private TreeColumn createColumn(Tree tree, TreeColumnLayout columnLayout, String text) { TreeColumn column = new TreeColumn(tree, SWT.NONE); column.setText(text); column.setMoveable(true); columnLayout.setColumnData(column, new ColumnWeightData(30)); return column; } @Override public void setFocus() {} private class LoadSummaryDataThread extends Thread { @Override public void run() { final String repositoryName = repositoryEditorInput.getName(); final RepositoryMetadata metadata = client.getRepository( new GetRepositoryRequest() .withRepositoryName(repositoryName)) .getRepositoryMetadata(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { lastModifiedDateText.setText(metadata.getLastModifiedDate().toString()); repositoryDescriptionText.setText(nonNullString(metadata.getRepositoryDescription())); cloneUrlHttpText.setText(metadata.getCloneUrlHttp()); cloneUrlSSHText.setText(metadata.getCloneUrlSsh()); } }); } } private class LoadBranchesThread extends Thread { @Override public void run() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { branchCombo.removeAll(); List<String> branches = client.listBranches(new ListBranchesRequest() .withRepositoryName(repositoryEditorInput.getRepository().getRepositoryName())) .getBranches(); if (!branches.isEmpty()) { for (String branch : branches) { branchCombo.add(branch); } String defautBranch = client.getRepository(new GetRepositoryRequest() .withRepositoryName(repositoryEditorInput.getRepository().getRepositoryName())) .getRepositoryMetadata().getDefaultBranch(); branchCombo.select(branchCombo.indexOf(defautBranch)); } new LoadCommitHistoryThread().start(); } }); } } private class LoadCommitHistoryThread extends Thread { @Override public void run() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { String repositoryName = repositoryEditorInput.getRepository().getRepositoryName(); String currentBranch = branchCombo.getText(); List<CommitRow> row = new ArrayList<>(); if (!StringUtils.isNullOrEmpty(currentBranch)) { String commitId = client.getBranch(new GetBranchRequest() .withRepositoryName(repositoryName) .withBranchName(currentBranch)) .getBranch().getCommitId(); int count = DEFAUT_COMMIT_HISTORY_COUNT; while (count-- > 0 && commitId != null) { Commit commit = client.getCommit(new GetCommitRequest() .withRepositoryName(repositoryName) .withCommitId(commitId)) .getCommit(); row.add(new CommitRow(commitId, commit)); List<String> parent = commit.getParents(); commitId = parent != null && !parent.isEmpty() ? parent.get(0) : null; } } viewer.setInput(row); } }); } } private class RefreshAction extends AwsAction { public RefreshAction() { super(AwsToolkitMetricType.EXPLORER_CODECOMMIT_REFRESH_REPO_EDITOR); this.setText("Refresh"); this.setToolTipText("Refresh CodeCommit Repository"); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor( AwsToolkitCore.IMAGE_REFRESH)); } @Override public void doRun() { new LoadSummaryDataThread().start(); new LoadBranchesThread().start(); actionFinished(); } } private final class CommitContentProvider implements ITreePathContentProvider { private CommitRow[] commits; @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput instanceof List) { commits = ((List<CommitRow>)newInput).toArray(new CommitRow[0]); } else { commits = new CommitRow[0]; } } @Override public void dispose() { } @Override public Object[] getChildren(TreePath arg0) { return null; } @Override public Object[] getElements(Object arg0) { return commits; } @Override public TreePath[] getParents(Object arg0) { return null; } @Override public boolean hasChildren(TreePath arg0) { return false; } } private final class CommitLabelProvider implements ITableLabelProvider { @Override public void addListener(ILabelProviderListener arg0) { } @Override public void dispose() { } @Override public boolean isLabelProperty(Object arg0, String arg1) { return false; } @Override public void removeListener(ILabelProviderListener arg0) { } @Override public Image getColumnImage(Object arg0, int arg1) { return null; } @Override public String getColumnText(Object obj, int column) { if (obj instanceof CommitRow == false) return ""; CommitRow message = (CommitRow) obj; switch (column) { case 0: return message.getCommitId(); case 1: return message.getCommit().getMessage(); case 2: return message.getCommit().getCommitter().getName(); case 3: return CodeCommitUtil.codeCommitTimeToHumanReadible(message.getCommit().getCommitter().getDate()); } return ""; } } // POJO class acting as the row data model for the commit history table. private final class CommitRow { private final String commitId; private final Commit commit; public CommitRow(String commitId, Commit commit) { this.commitId = commitId; this.commit = commit; } public String getCommitId() { return commitId; } public Commit getCommit() { return commit; } } private void onBranchSelected() { new LoadCommitHistoryThread().start(); } }
7,325
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/explorer/CodeCommitContentProvider.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.explorer; import java.util.Iterator; import java.util.List; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import com.amazonaws.eclipse.codecommit.explorer.CodeCommitActionProvider.OpenRepositoryEditorAction; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.explorer.AWSResourcesRootElement; import com.amazonaws.eclipse.explorer.AbstractContentProvider; import com.amazonaws.eclipse.explorer.Loading; import com.amazonaws.services.codecommit.AWSCodeCommit; import com.amazonaws.services.codecommit.model.ListRepositoriesRequest; import com.amazonaws.services.codecommit.model.RepositoryNameIdPair; public class CodeCommitContentProvider extends AbstractContentProvider implements ITreeContentProvider { private final IOpenListener listener = new IOpenListener() { @Override public void open(OpenEvent event) { StructuredSelection selection = (StructuredSelection) event.getSelection(); Iterator<?> i = selection.iterator(); while ( i.hasNext() ) { Object obj = i.next(); if ( obj instanceof RepositoryNameIdPair ) { RepositoryNameIdPair nameIdPair = (RepositoryNameIdPair) obj; OpenRepositoryEditorAction action = new OpenRepositoryEditorAction(nameIdPair); action.run(); } } } }; @Override public void dispose() { viewer.removeOpenListener(listener); super.dispose(); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { super.inputChanged(viewer, oldInput, newInput); this.viewer.addOpenListener(listener); } @Override public String getServiceAbbreviation() { return ServiceAbbreviations.CODECOMMIT; } @Override public Object[] loadChildren(final Object parentElement) { if ( parentElement instanceof AWSResourcesRootElement ) { return new Object[] { CodeCommitRootElement.ROOT_ELEMENT}; } if ( parentElement instanceof CodeCommitRootElement ) { new DataLoaderThread(parentElement) { @Override public Object[] loadData() { AWSCodeCommit codeCommit = AwsToolkitCore.getClientFactory() .getCodeCommitClient(); List<RepositoryNameIdPair> applications = codeCommit.listRepositories(new ListRepositoriesRequest()).getRepositories(); return applications.toArray(); } }.start(); } return Loading.LOADING; } @Override public boolean hasChildren(Object element) { return (element instanceof AWSResourcesRootElement || element instanceof CodeCommitRootElement); } }
7,326
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/explorer/CodeCommitRootElement.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.explorer; /** * CodeCommit root element in the AWS explorer. */ public class CodeCommitRootElement { public static CodeCommitRootElement ROOT_ELEMENT = new CodeCommitRootElement(); private CodeCommitRootElement() { } }
7,327
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/explorer/RepositoryEditorInput.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.explorer; import org.eclipse.jface.resource.ImageDescriptor; import com.amazonaws.eclipse.codecommit.CodeCommitPlugin; import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput; import com.amazonaws.services.codecommit.model.RepositoryNameIdPair; public class RepositoryEditorInput extends AbstractAwsResourceEditorInput { private final RepositoryNameIdPair repository; public RepositoryEditorInput(RepositoryNameIdPair repository, String regionEndpoint, String accountId, String regionId) { super(regionEndpoint, accountId, regionId); this.repository = repository; } @Override public ImageDescriptor getImageDescriptor() { return CodeCommitPlugin.getDefault().getImageRegistry().getDescriptor(CodeCommitPlugin.IMG_REPOSITORY); } public RepositoryNameIdPair getRepository() { return repository; } @Override public String getToolTipText() { return "AWS CodeCommit Repository Editor - " + repository.getRepositoryName(); } @Override public String getName() { return repository.getRepositoryName(); } }
7,328
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/explorer/CodeCommitLabelProvider.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.explorer; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import com.amazonaws.eclipse.codecommit.CodeCommitPlugin; import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider; import com.amazonaws.services.codecommit.model.RepositoryNameIdPair; public class CodeCommitLabelProvider extends ExplorerNodeLabelProvider { @Override public Image getDefaultImage(Object element) { ImageRegistry imageRegistry = CodeCommitPlugin.getDefault().getImageRegistry(); if ( element instanceof CodeCommitRootElement ) { return imageRegistry.get(CodeCommitPlugin.IMG_SERVICE); } if ( element instanceof RepositoryNameIdPair ) { return imageRegistry.get(CodeCommitPlugin.IMG_REPOSITORY); } return null; } @Override public String getText(Object element) { if ( element instanceof CodeCommitRootElement ) { return "AWS CodeCommit"; } if ( element instanceof RepositoryNameIdPair ) { return ((RepositoryNameIdPair) element).getRepositoryName(); } return getExplorerNodeText(element); } }
7,329
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/model/CodeCommitPreferencePageDataModel.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.model; import com.amazonaws.eclipse.core.model.GitCredentialsDataModel; public class CodeCommitPreferencePageDataModel { public static final String P_PROFILE = "profile"; private String profile; private GitCredentialsDataModel gitCredentialsDataModel = new GitCredentialsDataModel(); public String getProfile() { return profile; } public void setProfile(String profile) { this.profile = profile; } public GitCredentialsDataModel getGitCredentialsDataModel() { return gitCredentialsDataModel; } }
7,330
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/pages/GitCredentialsConfigurationPage.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.pages; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import com.amazonaws.eclipse.codecommit.widgets.GitCredentialsComposite; import com.amazonaws.eclipse.core.model.GitCredentialsDataModel; /** */ public class GitCredentialsConfigurationPage extends WizardPage { private final GitCredentialsDataModel dataModel; private GitCredentialsComposite gitCredentialsComposite; private final DataBindingContext dataBindingContext; private final AggregateValidationStatus aggregateValidationStatus; public GitCredentialsConfigurationPage(GitCredentialsDataModel dataModel) { super(GitCredentialsConfigurationPage.class.getName()); this.setTitle("Git Credential Configuration"); this.dataModel = dataModel; this.dataBindingContext = new DataBindingContext(); this.aggregateValidationStatus = new AggregateValidationStatus( dataBindingContext, AggregateValidationStatus.MAX_SEVERITY); aggregateValidationStatus.addChangeListener(new IChangeListener() { @Override public void handleChange(ChangeEvent arg0) { populateValidationStatus(); } }); } @Override public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); createGitCredentialsComposite(composite); setControl(composite); } private void createGitCredentialsComposite(Composite composite) { Group gitCredentialsGroup = newGroup(composite, "Configure Git Credentials:"); gitCredentialsGroup.setLayout(new GridLayout(1, false)); this.gitCredentialsComposite = new GitCredentialsComposite( gitCredentialsGroup, dataBindingContext, dataModel); } private void populateValidationStatus() { IStatus status = getValidationStatus(); if (status == null || status.getSeverity() == IStatus.OK) { this.setErrorMessage(null); super.setPageComplete(true); } else { setErrorMessage(status.getMessage()); super.setPageComplete(false); } } private IStatus getValidationStatus() { if (aggregateValidationStatus == null) return null; Object value = aggregateValidationStatus.getValue(); if (!(value instanceof IStatus)) return null; return (IStatus)value; } }
7,331
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/widgets/GitCredentialsComposite.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.widgets; import static com.amazonaws.eclipse.core.model.GitCredentialsDataModel.P_PASSWORD; import static com.amazonaws.eclipse.core.model.GitCredentialsDataModel.P_SHOW_PASSWORD; import static com.amazonaws.eclipse.core.model.GitCredentialsDataModel.P_USERNAME; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLink; import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newPushButton; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.HashSet; import java.util.Set; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import com.amazonaws.eclipse.codecommit.CodeCommitConstants; import com.amazonaws.eclipse.codecommit.credentials.GitCredential; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.model.GitCredentialsDataModel; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.eclipse.core.widget.CheckboxComplex; import com.amazonaws.eclipse.core.widget.TextComplex; import com.amazonaws.eclipse.databinding.NotEmptyValidator; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.model.AttachUserPolicyRequest; import com.amazonaws.services.identitymanagement.model.CreateServiceSpecificCredentialRequest; import com.amazonaws.services.identitymanagement.model.CreateUserRequest; import com.amazonaws.services.identitymanagement.model.LimitExceededException; import com.amazonaws.services.identitymanagement.model.ListUsersRequest; import com.amazonaws.services.identitymanagement.model.ListUsersResult; import com.amazonaws.services.identitymanagement.model.ServiceSpecificCredential; import com.amazonaws.services.identitymanagement.model.User; import com.amazonaws.util.StringUtils; /** * A complex composite for configuring Git credentials. */ public class GitCredentialsComposite extends Composite { private static final String AUTO_CREATE_GIT_CREDENTIALS_TILTE = "Auto-create Git credentials"; private static final String IAM_USER_PREFIX = "EclipseToolkit-CodeCommitUser"; private static final String GIT_CREDENTIALS_DOC = "http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html#setting-up-gc-iam"; private static final String CREATE_SERVICE_SPECIFIC_CREDENTIALS_DOC = "http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html"; private final DataBindingContext dataBindingContext; private final GitCredentialsDataModel dataModel; private TextComplex usernameComplex; private TextComplex passwordComplex; private CheckboxComplex showPasswordComplex; private Button browseButton; private Button createGitCredentialsButton; private IValidator usernameValidator; private IValidator passwordValidator; public GitCredentialsComposite(Composite parent, DataBindingContext dataBindingContext, GitCredentialsDataModel dataModel) { this(parent, dataBindingContext, dataModel, null, null); } public GitCredentialsComposite(Composite parent, DataBindingContext dataBindingContext, GitCredentialsDataModel dataModel, IValidator usernameValidator, IValidator passwordValidator) { super(parent, SWT.NONE); setLayout(new GridLayout(2, false)); setLayoutData(new GridData(GridData.FILL_BOTH)); this.dataModel = dataModel; this.dataBindingContext = dataBindingContext; this.usernameValidator = usernameValidator; this.passwordValidator = passwordValidator; createControl(); } public void populateGitCredential(String username, String password) { usernameComplex.setText(username); passwordComplex.setText(password); } private void createControl() { createUsernamePasswordSection(); createButtonCompositeSection(); onShowPasswordCheckboxSelection(); } private void createUsernamePasswordSection() { newLink(this, new WebLinkListener(), String.format( "You can manually copy and paste Git credentials for AWS CodeCommit below. " + "Alternately, you can import them from a downloaded .csv file. To learn how to generate Git credentials, see " + "<a href=\"%s\">Create Git Credentials for HTTPS Connections to AWS CodeCommit</a>. You can also authorize the AWS " + "Toolkit for Eclipse to create a new set of Git credentials under the current selected account. see " + "<a href=\"%s\">CreateServiceSpecificCredential</a> for more information.", GIT_CREDENTIALS_DOC, CREATE_SERVICE_SPECIFIC_CREDENTIALS_DOC), 2); usernameComplex = TextComplex.builder(this, dataBindingContext, PojoObservables.observeValue(dataModel, P_USERNAME)) .addValidator(usernameValidator == null ? new NotEmptyValidator("User name must be provided!") : usernameValidator) .labelValue("User name:") .defaultValue(dataModel.getUsername()) .build(); passwordComplex = TextComplex.builder(this, dataBindingContext, PojoObservables.observeValue(dataModel, P_PASSWORD)) .addValidator(passwordValidator == null ? new NotEmptyValidator("Password must be provided!") : passwordValidator) .labelValue("Password: ") .defaultValue(dataModel.getPassword()) .build(); } private void createButtonCompositeSection() { Composite buttonComposite = new Composite(this, SWT.NONE); buttonComposite.setLayout(new GridLayout(3, false)); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 2; buttonComposite.setLayoutData(gridData); showPasswordComplex = CheckboxComplex.builder() .composite(buttonComposite) .dataBindingContext(dataBindingContext) .pojoObservableValue(PojoObservables.observeValue(dataModel, P_SHOW_PASSWORD)) .labelValue("Show password") .selectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onShowPasswordCheckboxSelection(); } }) .defaultValue(dataModel.isShowPassword()) .build(); browseButton = newPushButton(buttonComposite, "Import from csv file"); browseButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(getShell(), SWT.SINGLE); String path = dialog.open(); if (path == null) { return; } GitCredential gitCredential = loadGitCredential(new File(path)); populateGitCredential(gitCredential.getUsername(), gitCredential.getPassword()); } }); createGitCredentialsButton = newPushButton(buttonComposite, "Create Git credentials"); createGitCredentialsButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); createGitCredentialsButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { AmazonIdentityManagement iam = dataModel.getIamClient(); String profileName = AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(dataModel.getUserAccount()).getAccountName(); try { String userName = iam.getUser().getUser().getUserName(); if (StringUtils.isNullOrEmpty(userName)) { if (!MessageDialog.openConfirm(getShell(), AUTO_CREATE_GIT_CREDENTIALS_TILTE, String.format("Your profile is using root AWS credentials. AWS CodeCommit requires specific CodeCommit credentials from an IAM user. " + "The toolkit can create an IAM user with CodeCommit credentials and associate the credentials with the %s Toolkit profile.\n\n" + "Proceed to try and create an IAM user with credentials and associate with the %s Toolkit profile?", profileName, profileName))) { return; } userName = createNewIamUser().getUserName(); } ServiceSpecificCredential credential = iam.createServiceSpecificCredential(new CreateServiceSpecificCredentialRequest() .withUserName(userName).withServiceName(CodeCommitConstants.CODECOMMIT_SERVICE_NAME)) .getServiceSpecificCredential(); populateGitCredential(credential.getServiceUserName(), credential.getServicePassword()); } catch (LimitExceededException lee) { MessageDialog.openWarning(getShell(), AUTO_CREATE_GIT_CREDENTIALS_TILTE, "You may already have created the maximum number of sets of Git credentials for AWS CodeCommit(two). " + "Log into the AWS Management Console to download the credentials or obtain them from your administrator, and then import to the toolkit."); } catch (Exception ex) { MessageDialog.openError(getShell(), AUTO_CREATE_GIT_CREDENTIALS_TILTE, "Error: " + ex.getMessage()); } } }); } // Create a new IAM user attched with the default policy, AWSCodeCommitPowerUser private User createNewIamUser() { AmazonIdentityManagement iam = dataModel.getIamClient(); Set<String> userSet = new HashSet<>(); ListUsersResult result = new ListUsersResult(); do { result = iam.listUsers(new ListUsersRequest().withMarker(result.getMarker())); for (User user : result.getUsers()) { userSet.add(user.getUserName()); } } while (result.isTruncated()); String newIamUserName = IAM_USER_PREFIX; for (int i = 1; userSet.contains(newIamUserName); ++i) { newIamUserName = IAM_USER_PREFIX + "-" + i; } User newUser = iam.createUser(new CreateUserRequest().withUserName(newIamUserName)).getUser(); iam.attachUserPolicy(new AttachUserPolicyRequest() .withUserName(newIamUserName) .withPolicyArn("arn:aws:iam::aws:policy/AWSCodeCommitPowerUser")); return newUser; } private void onShowPasswordCheckboxSelection() { passwordComplex.getText().setEchoChar(showPasswordComplex.getCheckbox().getSelection() ? '\0' : '*'); } private GitCredential loadGitCredential(File csvFile) { GitCredential gitCredential = new GitCredential("", ""); try (BufferedReader bufferedReader = new BufferedReader(new FileReader(csvFile))) { String line = bufferedReader.readLine(); // the first line of the default csv file is metadata if (line == null) { throw new ParseException("The csv file is empty", 1); } line = bufferedReader.readLine(); // the second line of the default csv file contains the credentials separated with ',' if (line == null) { throw new ParseException("Invalid Git credential csv file format!", 2); } String[] tokens = line.split(","); if (tokens.length != 2) { throw new ParseException( "The csv file must have two columns!", 2); } gitCredential.setUsername(tokens[0].trim()); gitCredential.setPassword(tokens[1].trim()); } catch (Exception e) { AwsToolkitCore.getDefault().logWarning("Failed to load gitCredentials file for Git credentials!", e); new MessageDialog(getShell(), "Error loading Git credentials!", null, e.getMessage(), MessageDialog.ERROR, new String[] {"OK"}, 0).open(); } return gitCredential; } }
7,332
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/credentials/GitCredential.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.credentials; public class GitCredential { private String username; private String password; public GitCredential(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
7,333
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.codecommit/src/com/amazonaws/eclipse/codecommit/credentials/GitCredentialsManager.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.codecommit.credentials; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.eclipse.jface.preference.IPreferenceStore; import com.amazonaws.eclipse.codecommit.CodeCommitPlugin; import com.amazonaws.eclipse.codecommit.preferences.PreferenceConstants; import com.amazonaws.eclipse.core.AccountInfo; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.accounts.AccountInfoChangeListener; import com.amazonaws.util.StringUtils; /** * Git credentials manager that manages Git credentials in between memory and disk. */ public class GitCredentialsManager { private static final Map<String, GitCredential> GIT_CREDENTIALS = new HashMap<>(); public static void init() { AwsToolkitCore.getDefault().getAccountManager().addAccountInfoChangeListener( AccountInfoChangeListenerForGitCredentials.INSTANCE); loadGitCredentials(); mergeAwsProfiles(); } /** * Load Git credentials from the Git credentials file and do a merge to the current credentials. */ public static void loadGitCredentials() { File gitCredentialsFile = getGitCredentialsFile(); if (gitCredentialsFile.exists() && gitCredentialsFile.isFile()) { try (BufferedReader bufferedReader = new BufferedReader(new FileReader(gitCredentialsFile))) { String line; int lineNumber = 0; while ((line = bufferedReader.readLine()) != null) { ++lineNumber; List<String> tokens = splitStringByComma(line); if (tokens.size() != 3) { CodeCommitPlugin.getDefault().logWarning("Invalid csv file: " + gitCredentialsFile.getAbsolutePath(), new ParseException("The csv file must have three columns!", lineNumber)); } else { GIT_CREDENTIALS.put(tokens.get(0).trim(), new GitCredential(tokens.get(1).trim(), tokens.get(2).trim())); } } } catch (Exception e) { AwsToolkitCore.getDefault().reportException("Failed to load gitCredentials file for git credentials!", e); } } } /** * Merge AWS account profiles to Git credentials manager. */ private static void mergeAwsProfiles() { Map<String, AccountInfo> accounts = AwsToolkitCore.getDefault().getAccountManager().getAllAccountInfo(); for (Entry<String, AccountInfo> entry : accounts.entrySet()) { String accountName = entry.getValue().getAccountName(); if (GIT_CREDENTIALS.containsKey(accountName)) continue; GIT_CREDENTIALS.put(accountName, new GitCredential("", "")); } } public static Map<String, GitCredential> getGitCredentials() { return GIT_CREDENTIALS; } public static GitCredential getGitCredential(String profile) { return GIT_CREDENTIALS.get(profile); } private static File getGitCredentialsFile() { IPreferenceStore store = CodeCommitPlugin.getDefault().getPreferenceStore(); String filePath = store.getString(PreferenceConstants.GIT_CREDENTIALS_FILE_PREFERENCE_NAME); return new File(StringUtils.isNullOrEmpty(filePath) ? PreferenceConstants.DEFAULT_GIT_CREDENTIALS_FILE : filePath); } public static void saveGitCredentials() { File gitCredentialsFile = getGitCredentialsFile(); if (!gitCredentialsFile.exists()) { try { gitCredentialsFile.createNewFile(); } catch (IOException e) { AwsToolkitCore.getDefault().reportException("Failed to create gitCredentials file!", e); } } try (PrintWriter writer = new PrintWriter(new FileWriter(gitCredentialsFile))) { for (Entry<String, GitCredential> entry : GIT_CREDENTIALS.entrySet()) { writer.println(String.format("%s,%s,%s",entry.getKey(), entry.getValue().getUsername(), entry.getValue().getPassword())); } writer.flush(); } catch (Exception e) { AwsToolkitCore.getDefault().logWarning("Failed to write git credential to file!", e); } } /** * Listens profile updating event to keep sync up with the Git credentials manager. */ private static class AccountInfoChangeListenerForGitCredentials implements AccountInfoChangeListener { public static AccountInfoChangeListenerForGitCredentials INSTANCE = new AccountInfoChangeListenerForGitCredentials(); private AccountInfoChangeListenerForGitCredentials() {} @Override public void onAccountInfoChange() { mergeAwsProfiles(); } } /** * The String.split method incorrectly parses "profile,," to {"profile"} instead of {"profile", "", ""}. * This helper method correctly parses cvs lines. */ private static List<String> splitStringByComma(String str) { List<String> tokens = new ArrayList<>(); int fromIndex = 0, endIndex = 0; while ((endIndex = str.indexOf(',', fromIndex)) > 0) { tokens.add(str.substring(fromIndex, endIndex)); fromIndex = endIndex + 1; } tokens.add(str.substring(fromIndex)); return tokens; } }
7,334
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/templates/worker
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/templates/worker/src/WorkerServlet.java
package {PACKAGE_NAME}; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.amazonaws.auth.AWSCredentialsProviderChain; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.auth.InstanceProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.ObjectMetadata; /** * An example Amazon Elastic Beanstalk Worker Tier application. This example * requires a Java 7 (or higher) compiler. */ public class WorkerServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Charset UTF_8 = Charset.forName("UTF-8"); /** * A client to use to access Amazon S3. Pulls credentials from the * {@code AwsCredentials.properties} file if found on the classpath, * otherwise will attempt to obtain credentials based on the IAM * Instance Profile associated with the EC2 instance on which it is * run. */ private final AmazonS3Client s3 = new AmazonS3Client( new AWSCredentialsProviderChain( new InstanceProfileCredentialsProvider(), new ProfileCredentialsProvider("{CREDENTIAL_PROFILE}"))); /** * This method is invoked to handle POST requests from the local * SQS daemon when a work item is pulled off of the queue. The * body of the request contains the message pulled off the queue. */ @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { try { // Parse the work to be done from the POST request body. WorkRequest workRequest = WorkRequest.fromJson(request.getInputStream()); // Simulate doing some work. Thread.sleep(10 * 1000); // Write the "result" of the work into Amazon S3. byte[] message = workRequest.getMessage().getBytes(UTF_8); s3.putObject(workRequest.getBucket(), workRequest.getKey(), new ByteArrayInputStream(message), new ObjectMetadata()); // Signal to beanstalk that processing was successful so this work // item should not be retried. response.setStatus(200); } catch (RuntimeException | InterruptedException exception) { // Signal to beanstalk that something went wrong while processing // the request. The work request will be retried several times in // case the failure was transient (eg a temporary network issue // when writing to Amazon S3). response.setStatus(500); try (PrintWriter writer = new PrintWriter(response.getOutputStream())) { exception.printStackTrace(writer); } } } }
7,335
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/templates/worker
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/templates/worker/src/WorkRequest.java
package {PACKAGE_NAME}; import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.databind.ObjectMapper; /** * A POJO representation of a work request. */ class WorkRequest { private static final ObjectMapper MAPPER = new ObjectMapper(); private String bucket; private String key; private String message; /** * Create a work request by parsing it from a JSON format. * * @param json the JSON document to parse * @return the parsed work request * @throws IOException on error parsing the document */ public static WorkRequest fromJson(final InputStream json) throws IOException { return MAPPER.readValue(json, WorkRequest.class); } /** * @return the Amazon S3 bucket to write to */ public String getBucket() { return bucket; } /** * @param value the Amazon S3 bucket to write to */ public void setBucket(final String value) { bucket = value; } /** * @return the Amazon S3 object key to write to */ public String getKey() { return key; } /** * @param value the Amazon S3 object key to write to */ public void setKey(final String value) { key = value; } /** * @return the message to write to Amazon S3 */ public String getMessage() { return message; } /** * @param value the message to write to Amazon S3 */ public void setMessage(final String value) { message = value; } /** * Serialize the work request to JSON. * * @return the serialized JSON * @throws IOException on error serializing the value */ public String toJson() throws IOException { return MAPPER.writeValueAsString(this); } }
7,336
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/Environment.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; 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.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jst.server.core.IWebModule; import org.eclipse.jst.server.core.internal.J2EEUtil; import org.eclipse.wst.server.core.IModule; import org.eclipse.wst.server.core.IModuleType; import org.eclipse.wst.server.core.internal.ServerWorkingCopy; import org.eclipse.wst.server.core.internal.facets.FacetUtil; import org.eclipse.wst.server.core.model.ServerDelegate; import com.amazonaws.eclipse.core.AccountInfo; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.elasticbeanstalk.util.ElasticBeanstalkClientExtensions; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest; import com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest; import com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult; import com.amazonaws.services.ec2.model.IpPermission; import com.amazonaws.services.ec2.model.SecurityGroup; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationSettingsDescription; import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationSettingsRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentResourcesRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentResourcesResult; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; import com.amazonaws.services.elasticbeanstalk.model.Instance; @SuppressWarnings("restriction") public class Environment extends ServerDelegate { private static final String PROPERTY_REGION_ID = "regionId"; private static final String PROPERTY_REGION_ENDPOINT = "regionEndpoint"; private static final String PROPERTY_APPLICATION_NAME = "applicationName"; private static final String PROPERTY_APPLICATION_DESCRIPTION = "applicationDescription"; private static final String PROPERTY_ENVIRONMENT_NAME = "environmentName"; private static final String PROPERTY_ENVIRONMENT_TIER = "environmentTier"; private static final String PROPERTY_ENVIRONMENT_TYPE = "environmentType"; private static final String PROPERTY_ENVIRONMENT_DESCRIPTION = "environmentDescription"; private static final String PROPERTY_KEY_PAIR_NAME = "keyPairName"; private static final String PROPERTY_CNAME = "cname"; private static final String PROPERTY_HEALTHCHECK_URL = "healthcheckUrl"; private static final String PROPERTY_SSL_CERT_ID = "sslCertId"; private static final String PROPERTY_ACCOUNT_ID = "accountId"; private static final String PROPERTY_SNS_ENDPOINT = "snsEndpoint"; private static final String PROPERTY_SOLUTION_STACK = "solutionStack"; private static final String PROPERTY_INCREMENTAL_DEPLOYMENT = "incrementalDeployment"; private static final String PROPERTY_INSTANCE_ROLE_NAME = "instanceRoleName"; private static final String PROPERTY_SERVICE_ROLE_NAME = "serviceRoleName"; private static final String PROPERTY_SKIP_IAM_ROLE_AND_INSTANCE_PROFILE_CREATION = "skipIamRoleAndInstanceProfileCreation"; private static final String PROPERTY_WORKER_QUEUE_URL = "workerQueueUrl"; private static final String PROPERTY_VPC_ID = "vpcId"; private static final String PROPERTY_SUBNETS = "subnets"; private static final String PROPERTY_ELB_SUBNETS = "elbSubnets"; private static final String PROPERTY_ELB_SCHEME = "elbScheme"; private static final String PROPERTY_SECURITY_GROUP = "securityGroup"; private static final String PROPERTY_ASSOCIATE_PUBLIC_IP_ADDRESS = "associatePublicIpAddress"; private static Map<String, EnvironmentDescription> map = new HashMap<>(); @Override public void setDefaults(IProgressMonitor monitor) { // Disable auto publishing setAttribute("auto-publish-setting", 1); } public String getAccountId() { return getAttribute(PROPERTY_ACCOUNT_ID, (String)null); } public void setAccountId(String accountId) { setAttribute(PROPERTY_ACCOUNT_ID, accountId); } public String getRegionEndpoint() { return RegionUtils.getRegion(getRegionId()).getServiceEndpoints().get(ServiceAbbreviations.BEANSTALK); } public String getApplicationName() { return getAttribute(PROPERTY_APPLICATION_NAME, (String)null); } public void setApplicationName(String applicationName) { setAttribute(PROPERTY_APPLICATION_NAME, applicationName); } public String getApplicationDescription() { return getAttribute(PROPERTY_APPLICATION_NAME, (String)null); } public void setApplicationDescription(String applicationDescription) { setAttribute(PROPERTY_APPLICATION_DESCRIPTION, applicationDescription); } public String getEnvironmentTier() { return getAttribute(PROPERTY_ENVIRONMENT_TIER, (String) null); } public void setEnvironmentTier(String environmentTier) { setAttribute(PROPERTY_ENVIRONMENT_TIER, environmentTier); } public void setEnvironmentType(String environmentType) { setAttribute(PROPERTY_ENVIRONMENT_TYPE, environmentType); } public String getEnvironmentType() { return getAttribute(PROPERTY_ENVIRONMENT_TYPE, (String)null); } public String getEnvironmentName() { return getAttribute(PROPERTY_ENVIRONMENT_NAME, (String)null); } public void setEnvironmentName(String environmentName) { setAttribute(PROPERTY_ENVIRONMENT_NAME, environmentName); } public String getEnvironmentDescription() { return getAttribute(PROPERTY_ENVIRONMENT_DESCRIPTION, (String)null); } public void setEnvironmentDescription(String environmentDescription) { setAttribute(PROPERTY_ENVIRONMENT_DESCRIPTION, environmentDescription); } public String getEnvironmentUrl() { EnvironmentDescription cachedEnvironmentDescription = getCachedEnvironmentDescription(); if (cachedEnvironmentDescription == null) { return null; } if (cachedEnvironmentDescription.getCNAME() == null) { return null; } return "http://" + cachedEnvironmentDescription.getCNAME(); } public String getCname() { return getAttribute(PROPERTY_CNAME, (String)null); } public void setCname(String cname) { setAttribute(PROPERTY_CNAME, cname); } public String getKeyPairName() { return getAttribute(PROPERTY_KEY_PAIR_NAME, (String) null); } public void setKeyPairName(String keyPairName) { setAttribute(PROPERTY_KEY_PAIR_NAME, keyPairName); } public String getSslCertificateId() { return getAttribute(PROPERTY_SSL_CERT_ID, (String) null); } public void setSslCertificateId(String sslCertificateId) { setAttribute(PROPERTY_SSL_CERT_ID, sslCertificateId); } public String getHealthCheckUrl() { return getAttribute(PROPERTY_HEALTHCHECK_URL, (String)null); } public void setHealthCheckUrl(String healthCheckUrl) { setAttribute(PROPERTY_HEALTHCHECK_URL, healthCheckUrl); } public String getSnsEndpoint() { return getAttribute(PROPERTY_SNS_ENDPOINT, (String)null); } public void setSnsEndpoint(String snsEndpoint) { setAttribute(PROPERTY_SNS_ENDPOINT, snsEndpoint); } public String getSolutionStack() { return getAttribute(PROPERTY_SOLUTION_STACK, (String)null); } public void setSolutionStack(String solutionStackForServerType) { setAttribute(PROPERTY_SOLUTION_STACK, solutionStackForServerType); } public boolean getIncrementalDeployment() { return getAttribute(PROPERTY_INCREMENTAL_DEPLOYMENT, false); } public void setIncrementalDeployment(boolean incrementalDeployment) { setAttribute(PROPERTY_INCREMENTAL_DEPLOYMENT, incrementalDeployment); } public void setRegionId(String regionName) { setAttribute(PROPERTY_REGION_ID, regionName); } public String getRegionId() { return getAttribute(PROPERTY_REGION_ID, (String)null); } /** * Sets the name for the optional instance IAM role for this environment. If a role is * specified, the EC2 instances launched in this environment will have that * role available, including secure credentials distribution. * * @param instanceRoleName * The name for a valid instance IAM role. */ public void setInstanceRoleName(String instanceRoleName) { setAttribute(PROPERTY_INSTANCE_ROLE_NAME, instanceRoleName); } /** * Returns the name of the optional IAM role for this environment. If a role * is specified, the EC2 instances launched in this environment will have * that role available, including secure credentials distribution. * * @return The name of a valid IAM role. */ public String getInstanceRoleName() { return getAttribute(PROPERTY_INSTANCE_ROLE_NAME, (String)null); } /** * Sets the name of the optional IAM role that the service (ElasticBeanstalk) is allowed to * impersonate. Currently this is only used for Enhanced Health reporting/monitoring * * @param serviceRoleName * The name of the role that ElasticBeanstalk can assume */ public void setServiceRoleName(String serviceRoleName) { setAttribute(PROPERTY_SERVICE_ROLE_NAME, serviceRoleName); } /** * Returns the name of the optional IAM role that the service (ElasticBeanstalk) is allowed to * impersonate. Currently this is only used for Enhanced Health reporting/monitoring * * @return The name of the role that ElasticBeanstalk can assume */ public String getServiceRoleName() { return getAttribute(PROPERTY_SERVICE_ROLE_NAME, (String) null); } /** * Sets the id of the optional VPC that the service (ElasticBeanstalk) is to be deployed. * * @param vpcId * The id of the VPC that ElasticBeanstalk will be deployed to. */ public void setVpcId(String vpcId) { setAttribute(PROPERTY_VPC_ID, vpcId); } public String getVpcId() { return getAttribute(PROPERTY_VPC_ID, (String) null); } public void setSubnets(String subnets) { setAttribute(PROPERTY_SUBNETS, subnets); } public String getSubnets() { return getAttribute(PROPERTY_SUBNETS, (String) null); } public void setElbSubnets(String elbSubnets) { setAttribute(PROPERTY_ELB_SUBNETS, elbSubnets); } public String getElbSubnets() { return getAttribute(PROPERTY_ELB_SUBNETS, (String) null); } public void setElbScheme(String elbScheme) { setAttribute(PROPERTY_ELB_SCHEME, elbScheme); } public String getElbScheme() { return getAttribute(PROPERTY_ELB_SCHEME, (String) null); } public void setSecurityGroup(String securityGroup) { setAttribute(PROPERTY_SECURITY_GROUP, securityGroup); } public String getSecurityGroup() { return getAttribute(PROPERTY_SECURITY_GROUP, (String) null); } public void setAssociatePublicIpAddress(boolean associatePublicIpAddress) { setAttribute(PROPERTY_ASSOCIATE_PUBLIC_IP_ADDRESS, associatePublicIpAddress); } public boolean getAssociatePublicIpAddress() { return getAttribute(PROPERTY_ASSOCIATE_PUBLIC_IP_ADDRESS, false); } public void setSkipIamRoleAndInstanceProfileCreation(boolean skip) { setAttribute(PROPERTY_SKIP_IAM_ROLE_AND_INSTANCE_PROFILE_CREATION, skip); } public boolean isSkipIamRoleAndInstanceProfileCreation() { return getAttribute(PROPERTY_SKIP_IAM_ROLE_AND_INSTANCE_PROFILE_CREATION, false); } public String getWorkerQueueUrl() { return getAttribute(PROPERTY_WORKER_QUEUE_URL, (String) null); } public void setWorkerQueueUrl(String url) { setAttribute(PROPERTY_WORKER_QUEUE_URL, url); } /* * TODO: We can't quite turn this on yet because WTPWarUtils runs an operation that tries to lock * the whole workspace when it exports the WAR for a project. If we can figure out how to * get that to not lock the whole workspace, then we can turn this back on. */ // public boolean isUseProjectSpecificSchedulingRuleOnPublish() { // return true; // } /* (non-Javadoc) * @see org.eclipse.wst.server.core.model.ServerDelegate#canModifyModules(org.eclipse.wst.server.core.IModule[], org.eclipse.wst.server.core.IModule[]) */ @Override public IStatus canModifyModules(IModule[] add, IModule[] remove) { // If we're not adding any modules, we know this request is fine if (add == null) { return Status.OK_STATUS; } if (add.length > 1) { return new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Only one web application can run in each AWS Elastic Beanstalk environment"); } for (IModule module : add) { String moduleTypeId = module.getModuleType().getId().toLowerCase(); if (moduleTypeId.equals("jst.web") == false) { return new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unsupported module type: " + module.getModuleType().getName()); } if (module.getProject() != null) { IStatus status = FacetUtil.verifyFacets(module.getProject(), getServer()); if (status != null && !status.isOK()) { return status; } } } return Status.OK_STATUS; } /* (non-Javadoc) * @see org.eclipse.wst.server.core.model.ServerDelegate#getChildModules(org.eclipse.wst.server.core.IModule[]) */ @Override public IModule[] getChildModules(IModule[] module) { if (module == null) { return null; } IModuleType moduleType = module[0].getModuleType(); if (module.length == 1 && moduleType != null && "jst.web".equalsIgnoreCase(moduleType.getId())) { IWebModule webModule = (IWebModule)module[0].loadAdapter(IWebModule.class, null); if (webModule != null) { return webModule.getModules(); } } return new IModule[0]; } /* (non-Javadoc) * @see org.eclipse.wst.server.core.model.ServerDelegate#getRootModules(org.eclipse.wst.server.core.IModule) */ @Override public IModule[] getRootModules(IModule module) throws CoreException { String moduleTypeId = module.getModuleType().getId().toLowerCase(); if (moduleTypeId.equals("jst.web")) { IStatus status = canModifyModules(new IModule[] {module}, null); if (status == null || !status.isOK()) { throw new CoreException(status); } return new IModule[] {module}; } return J2EEUtil.getWebModules(module, null); } /* (non-Javadoc) * @see org.eclipse.wst.server.core.model.ServerDelegate#modifyModules(org.eclipse.wst.server.core.IModule[], org.eclipse.wst.server.core.IModule[], org.eclipse.core.runtime.IProgressMonitor) */ @Override public void modifyModules(IModule[] add, IModule[] remove, IProgressMonitor monitor) throws CoreException { IStatus status = canModifyModules(add, remove); if (status == null || !status.isOK()) { throw new CoreException(status); } if (add != null && add.length > 0 && getServer().getModules().length > 0) { ServerWorkingCopy serverWorkingCopy = (ServerWorkingCopy)getServer(); serverWorkingCopy.modifyModules(new IModule[0], serverWorkingCopy.getModules(), monitor); } } public void setCachedEnvironmentDescription(EnvironmentDescription environmentDescription) { map.put(getServer().getId(), environmentDescription); } public EnvironmentDescription getCachedEnvironmentDescription() { return map.get(getServer().getId()); } /* * Utility methods for communicating with environments */ /** * Returns the environment's configured remote debugging port, or null if it * cannot be determined. */ public static String getDebugPort(List<ConfigurationSettingsDescription> settings) { ConfigurationOptionSetting opt = Environment.getJVMOptions(settings); if ( opt != null ) { return getDebugPort(opt.getValue()); } return null; } /** * Returns the debug port in the JVM options string given, or null if it isn't present. */ public static String getDebugPort(String jvmOptions) { if ( jvmOptions.contains("-Xdebug") && jvmOptions.contains("-Xrunjdwp:") ) { Matcher matcher = Pattern.compile("-Xrunjdwp:\\S*address=(\\d+)").matcher(jvmOptions); if ( matcher.find() && matcher.groupCount() > 0 && matcher.group(1) != null ) { return matcher.group(1); } } return null; } /** * Returns the "JVM Options" configuration setting, if it exists, or null otherwise. */ public static ConfigurationOptionSetting getJVMOptions(List<ConfigurationSettingsDescription> settings) { for (ConfigurationSettingsDescription setting : settings) { for (ConfigurationOptionSetting opt : setting.getOptionSettings()) { if (opt.getOptionName().equals("JVM Options") && opt.getNamespace().equals(ConfigurationOptionConstants.JVMOPTIONS)) { return opt; } } } return null; } /** * Returns the security group name given in the configuration settings, or null if it cannot be determined. */ public static String getSecurityGroup(List<ConfigurationSettingsDescription> settings) { for (ConfigurationSettingsDescription setting : settings) { for (ConfigurationOptionSetting opt : setting.getOptionSettings()) { if (opt.getOptionName().equals("SecurityGroups") && opt.getNamespace().equals(ConfigurationOptionConstants.LAUNCHCONFIGURATION)) { return opt.getValue(); } } } return null; } /** * Returns whether the given port is open on the security group for the * environment settings given. */ public boolean isIngressAllowed(int port, List<ConfigurationSettingsDescription> settings) { String securityGroup = Environment.getSecurityGroup(settings); if (securityGroup == null) { throw new RuntimeException("Couldn't determine security group of environent"); } AmazonEC2 ec2 = getEc2Client(); DescribeSecurityGroupsResult describeSecurityGroups = ec2.describeSecurityGroups(new DescribeSecurityGroupsRequest().withGroupNames(securityGroup)); for (SecurityGroup group : describeSecurityGroups.getSecurityGroups()) { if (ingressAllowed(group, port)) { return true; } } return false; } /** * @see Environment#isIngressAllowed(int, List) */ public boolean isIngressAllowed(String port, List<ConfigurationSettingsDescription> settings) { return isIngressAllowed(Integer.parseInt(port), settings); } /** * Returns an EC2 client configured to talk to the appropriate region for * this environment. */ public AmazonEC2 getEc2Client() { return AwsToolkitCore.getClientFactory(getAccountId()).getEC2ClientByEndpoint( RegionUtils.getRegion(getRegionId()).getServiceEndpoint(ServiceAbbreviations.EC2)); } /** * Returns whether the group given allows TCP ingress on the port given. */ private boolean ingressAllowed(SecurityGroup group, int debugPortInt) { for (IpPermission permission : group.getIpPermissions()) { if ("tcp".equals(permission.getIpProtocol()) && permission.getIpRanges() != null && permission.getIpRanges().contains("0.0.0.0/0")) { if (permission.getFromPort() != null && permission.getFromPort() <= debugPortInt && permission.getToPort() != null && permission.getToPort() >= debugPortInt) { return true; } } } return false; } /** * Returns true if the Beanstalk environment represented by this WTP server has been created * yet. */ public boolean doesEnvironmentExistInBeanstalk() { return new ElasticBeanstalkClientExtensions(this).doesEnvironmentExist(getApplicationName(), getEnvironmentName()); } /** * Returns the list of current settings for this environment */ public List<ConfigurationSettingsDescription> getCurrentSettings() { if (doesEnvironmentExistInBeanstalk() == false) { return new ArrayList<>(); } AWSElasticBeanstalk beanstalk = getClient(); return beanstalk.describeConfigurationSettings( new DescribeConfigurationSettingsRequest().withEnvironmentName(getEnvironmentName()) .withApplicationName(getApplicationName())).getConfigurationSettings(); } /** * Returns a client for this environment. */ public AWSElasticBeanstalk getClient() { AccountInfo account = AwsToolkitCore.getDefault() .getAccountManager() .getAccountInfo(getAccountId()); //TODO: better way to handle this if (account == null) { // Fall back to the current account account = AwsToolkitCore.getDefault().getAccountInfo(); } return AwsToolkitCore.getClientFactory(account.getInternalAccountId()) .getElasticBeanstalkClientByEndpoint(getRegionEndpoint()); } /** * Opens up the port given on the security group for the environment * settings given. */ public void openSecurityGroupPort(int debugPort, String securityGroup) { getEc2Client().authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest().withCidrIp("0.0.0.0/0") .withFromPort(debugPort).withToPort(debugPort).withIpProtocol("tcp") .withGroupName(securityGroup)); } /** * @see Environment#openSecurityGroupPort(int, String) */ public void openSecurityGroupPort(String debugPort, String securityGroup) { openSecurityGroupPort(Integer.parseInt(debugPort), securityGroup); } /** * Returns the EC2 instance IDs being used by this environment. */ public List<String> getEC2InstanceIds() { AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(getAccountId()) .getElasticBeanstalkClientByEndpoint(getRegionEndpoint()); DescribeEnvironmentResourcesResult describeEnvironmentResources = client .describeEnvironmentResources(new DescribeEnvironmentResourcesRequest() .withEnvironmentName(getEnvironmentName())); List<String> instanceIds = new ArrayList<>(describeEnvironmentResources.getEnvironmentResources() .getInstances().size()); for ( Instance i : describeEnvironmentResources.getEnvironmentResources().getInstances() ) { instanceIds.add(i.getId()); } return instanceIds; } /** * We change the data model to save the server environment information. This * function is used to convert the old data format to the new one. */ public void convertLegacyServer() { String regionEndpoint = null; if ((getRegionId() == null) && ((regionEndpoint = getAttribute(PROPERTY_REGION_ENDPOINT, (String)null)) != null)) { setAttribute(PROPERTY_REGION_ID, RegionUtils.getRegionByEndpoint(regionEndpoint).getId()); } } public static String catSubnetList(Set<String> subnetList) { if (null == subnetList || subnetList.isEmpty()) { return ""; } Iterator<String> iterator = subnetList.iterator(); StringBuilder builder = new StringBuilder(iterator.next()); while (iterator.hasNext()) { builder.append(","); builder.append(iterator.next()); } return builder.toString(); } }
7,337
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/CantConnectDialog.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.elasticbeanstalk; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.Hyperlink; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.BrowserUtils; /** * Dialog to inform the user that they can't connect to AWS Elastic Beanstalk, with a * customizable message. */ public class CantConnectDialog extends MessageDialog { public CantConnectDialog(String message) { super(Display.getDefault().getActiveShell(), "Unable to connect to AWS Elastic Beanstalk", AwsToolkitCore.getDefault().getImageRegistry() .get(AwsToolkitCore.IMAGE_AWS_ICON), message, 0, new String[] { "OK" }, 0); } @Override protected Control createCustomArea(Composite parent) { final Hyperlink link = new Hyperlink(parent, SWT.NONE); link.setText("Click here to learn more about AWS Elastic Beanstalk"); link.setHref("https://aws.amazon.com/elasticbeanstalk/"); link.setUnderlined(true); link.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { BrowserUtils.openExternalBrowser(link.getHref().toString()); } }); return parent; } }
7,338
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ConfigurationOptionConstants.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.elasticbeanstalk; public interface ConfigurationOptionConstants { public static final String ENVIRONMENT = "aws:elasticbeanstalk:application:environment"; public static final String HOSTMANAGER = "aws:elasticbeanstalk:hostmanager"; public static final String JVMOPTIONS = "aws:elasticbeanstalk:container:tomcat:jvmoptions"; public static final String SNS_TOPICS = "aws:elasticbeanstalk:sns:topics"; public static final String APPLICATION = "aws:elasticbeanstalk:application"; public static final String ENVIRONMENT_TYPE = "aws:elasticbeanstalk:environment"; public static final String HEALTH_REPORTING_SYSTEM = "aws:elasticbeanstalk:healthreporting:system"; public static final String SQSD = "aws:elasticbeanstalk:sqsd"; public static final String TRIGGER = "aws:autoscaling:trigger"; public static final String ASG = "aws:autoscaling:asg"; public static final String POLICIES = "aws:elb:policies"; public static final String HEALTHCHECK = "aws:elb:healthcheck"; public static final String LOADBALANCER = "aws:elb:loadbalancer"; public static final String LAUNCHCONFIGURATION = "aws:autoscaling:launchconfiguration"; public static final String VPC = "aws:ec2:vpc"; public static final String WEB_SERVER = "WebServer"; public static final String WORKER = "Worker"; public static final String SINGLE_INSTANCE_ENV = "Single Instance Web Server Environment"; public static final String LOAD_BALANCED_ENV = "Load Balanced Web Server Environment"; public static final String WORKER_ENV = "Worker Environment"; public static final String COMMAND = "aws:elasticbeanstalk:command"; }
7,339
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/NoCredentialsDialog.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.elasticbeanstalk; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.forms.widgets.Hyperlink; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.ui.overview.HyperlinkHandler; /** * Simple dialog to inform users that they need to configure their AWS credentials. */ public class NoCredentialsDialog extends MessageDialog { public NoCredentialsDialog() { super(Display.getDefault().getActiveShell(), "Invalid AWS credentials", AwsToolkitCore.getDefault().getImageRegistry() .get(AwsToolkitCore.IMAGE_AWS_ICON), "No AWS security credentials configured", 0, new String[] { "OK" }, 0); } @Override protected Control createDialogArea(Composite parent) { return createComposite(parent); } /** * Creates and returns a composite with the "no credentials" message. * Assumes a GridLayout for the parent. */ public static Composite createComposite(Composite parent) { GridData gridData = new GridData(SWT.LEFT, SWT.TOP, false, false); gridData.horizontalSpan = 1; Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); Label label = new Label(composite, SWT.WRAP); label.setText("Your AWS security credentials aren't configured yet"); label.setLayoutData(gridData); Hyperlink preferenceLink = new Hyperlink(composite, SWT.WRAP); preferenceLink.setText("Open the AWS Toolkit for Eclipse preferences to enter your credentials."); preferenceLink.setLayoutData(gridData); preferenceLink.setHref("preference:" + AwsToolkitCore.ACCOUNT_PREFERENCE_PAGE_ID); preferenceLink.setUnderlined(true); preferenceLink.addHyperlinkListener(new HyperlinkHandler()); return composite; } }
7,340
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ElasticBeanstalkHttpLaunchable.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.elasticbeanstalk; import static com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin.trace; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.jst.server.core.Servlet; import org.eclipse.wst.server.core.IModuleArtifact; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.model.ServerDelegate; import org.eclipse.wst.server.core.util.HttpLaunchable; import org.eclipse.wst.server.core.util.WebResource; import com.amazonaws.eclipse.elasticbeanstalk.util.ElasticBeanstalkClientExtensions; import com.amazonaws.util.StringUtils; /** * Implementation of HttpLaunchable that delays resolving the environment's URL until getURL is * called. This allows us to create the HttpLaunchable object before the environment is created, and * before we know the final URL. */ public class ElasticBeanstalkHttpLaunchable extends HttpLaunchable { private URL url; private final IServer server; private final IModuleArtifact moduleArtifact; public ElasticBeanstalkHttpLaunchable(IServer server, IModuleArtifact moduleArtifact) { super((URL) null); this.server = server; this.moduleArtifact = moduleArtifact; } @Override public URL getURL() { initializeUrl(); return url; } /** * Sets the host name for this URL used by this adapter. */ public synchronized void setHost(String hostname) throws MalformedURLException { this.url = new URL("http://" + hostname + getModuleArtifactPath(moduleArtifact)); } /** * Clears the host URL for this adapter */ public synchronized void clearHost() { this.url = null; } private synchronized void initializeUrl() { if (url == null) { try { /* * We need to ask Elastic Beanstalk for the environment's URL at some point. It * could be here, or it could be cached in the environment object from earlier. */ Object serverDelegate = server.loadAdapter(ServerDelegate.class, null); if (serverDelegate instanceof Environment == false) { return; } Environment environment = (Environment) serverDelegate; final String environmentCname = appendTrailingSlashIfNotPresent(getCname(environment)); url = new URL("http://" + environmentCname + getModuleArtifactPath(moduleArtifact)); trace("Initializing module artifact URL: " + url.toString()); } catch (Exception e) { ElasticBeanstalkPlugin.getDefault().logError("Unable to determine environment URL:" + e.getMessage(), e); } } } private String getCname(Environment environment) { return new ElasticBeanstalkClientExtensions(environment).getEnvironmentCname(environment.getEnvironmentName()); } @Override public String toString() { return getClass().getSimpleName() + "[moduleArtifact=" + moduleArtifact.toString() + "]"; } private String getModuleArtifactPath(IModuleArtifact moduleArtifact) { if (moduleArtifact instanceof Servlet) { return getServletArtifactPath((Servlet) moduleArtifact); } else if (moduleArtifact instanceof WebResource) { return getWebResourceArtifactPath((WebResource) moduleArtifact); } else { return null; } } private String getServletArtifactPath(Servlet servlet) { if (servlet.getAlias() != null) { return trimLeadingSlashIfPresent(servlet.getAlias()); } else { return "servlet/" + servlet.getServletClassName(); } } private String getWebResourceArtifactPath(WebResource resource) { final String path = trimLeadingSlashIfPresent(resource.getPath().toString()); if (StringUtils.isNullOrEmpty(path)) { return ""; } else { return path; } } private String trimLeadingSlashIfPresent(final String path) { if (path != null && path.startsWith("/")) { return path.substring(1); } return path; } private String appendTrailingSlashIfNotPresent(final String path) { if (path != null && !path.endsWith("/")) { return path + "/"; } return path; } }
7,341
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ElasticBeanstalkLaunchConfigurationDelegate.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jdt.launching.AbstractJavaLaunchConfigurationDelegate; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.ServerUtil; import org.eclipse.wst.server.core.model.ServerBehaviourDelegate; public class ElasticBeanstalkLaunchConfigurationDelegate extends AbstractJavaLaunchConfigurationDelegate{ /* (non-Javadoc) * @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor) */ @Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { IServer server = ServerUtil.getServer(configuration); if (server == null) throw new RuntimeException("unknown server"); EnvironmentBehavior environmentBehavior = (EnvironmentBehavior) server.loadAdapter(ServerBehaviourDelegate.class, null); environmentBehavior.setupLaunch(launch, mode, monitor); } }
7,342
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/WtpConstantsUtils.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.ServerEvent; public class WtpConstantsUtils { public static String lookupPublishKind(int publishKind) { switch (publishKind) { case IServer.PUBLISH_AUTO: return "PUBLISH_AUTO"; case IServer.PUBLISH_CLEAN: return "PUBLISH_CLEAN"; case IServer.PUBLISH_FULL: return "PUBLISH_FULL"; case IServer.PUBLISH_INCREMENTAL: return "PUBLISH_INCREMENTAL"; default: return "???"; } } public static String lookupDeltaKind(int deltaKind) { switch (deltaKind) { case EnvironmentBehavior.ADDED: return "ADDED"; case EnvironmentBehavior.CHANGED: return "CHANGED"; case EnvironmentBehavior.NO_CHANGE: return "NO_CHANGE"; case EnvironmentBehavior.REMOVED: return "REMOVED"; default: return "???"; } } public static String lookupServerEventKind(int kind) { if ((kind & ServerEvent.MODULE_CHANGE) > 0) return "MODULE_CHANGE"; if ((kind & ServerEvent.SERVER_CHANGE) > 0) return "SERVER_CHANGE"; switch (kind) { case ServerEvent.MODULE_CHANGE: return "MODULE_CHANGE"; case ServerEvent.PUBLISH_STATE_CHANGE: return "PUBLISH_STATE_CHANGE"; case ServerEvent.RESTART_STATE_CHANGE: return "RESTART_STATE_CHANGE"; case ServerEvent.SERVER_CHANGE: return "SERVER_CHANGE"; case ServerEvent.STATE_CHANGE: return "STATE_CHANGE"; default: return "???"; } } public static String lookupState(int state) { switch (state) { case IServer.STATE_STARTED: return "STATE_STARTED"; case IServer.STATE_STARTING: return "STATE_STARTING"; case IServer.STATE_STOPPED: return "STATE_STOPPED"; case IServer.STATE_STOPPING: return "STATE_STOPPING"; case IServer.STATE_UNKNOWN: return "STATE_UNKNOWN"; default: return "???"; } } public static String lookupPublishState(int state) { switch (state) { case IServer.PUBLISH_STATE_FULL: return "PUBLISH_STATE_FULL"; case IServer.PUBLISH_STATE_INCREMENTAL: return "PUBLISH_STATE_INCREMENTAL"; case IServer.PUBLISH_STATE_NONE: return "PUBLISH_STATE_NONE"; case IServer.PUBLISH_STATE_UNKNOWN: return "PUBLISH_STATE_UNKNOWN"; default: return "???"; } } }
7,343
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/OpenEnvironmentUrlAction.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.wst.server.core.IServer; import com.amazonaws.eclipse.core.BrowserUtils; public class OpenEnvironmentUrlAction implements IObjectActionDelegate { private String environmentUrl; @Override public void run(IAction action) { if (environmentUrl != null) BrowserUtils.openExternalBrowser(environmentUrl); } @Override public void selectionChanged(IAction action, ISelection selection) { StructuredSelection structuredSelection = (StructuredSelection)selection; IServer selectedServer = (IServer)structuredSelection.getFirstElement(); if (selectedServer != null) { Environment environment = (Environment)selectedServer.loadAdapter(Environment.class, null); environmentUrl = environment.getEnvironmentUrl(); } action.setEnabled(selectedServer != null && selectedServer.getServerState() == IServer.STATE_STARTED); } @Override public void setActivePart(IAction action, IWorkbenchPart targetPart) {} }
7,344
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ElasticBeanstalkPublishingUtils.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import static com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin.trace; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.CoreException; 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.ui.statushandlers.StatusManager; import org.eclipse.wst.server.core.IModule; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.eclipse.core.AWSClientFactory; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.elasticbeanstalk.resources.BeanstalkResourceProvider; import com.amazonaws.eclipse.elasticbeanstalk.solutionstacks.SolutionStacks; import com.amazonaws.eclipse.elasticbeanstalk.util.BeanstalkConstants; import com.amazonaws.eclipse.elasticbeanstalk.util.ElasticBeanstalkClientExtensions; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.ApplicationVersionDescription; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting; import com.amazonaws.services.elasticbeanstalk.model.CreateApplicationRequest; import com.amazonaws.services.elasticbeanstalk.model.CreateApplicationVersionRequest; import com.amazonaws.services.elasticbeanstalk.model.CreateEnvironmentRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeEventsRequest; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentHealth; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentStatus; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentTier; import com.amazonaws.services.elasticbeanstalk.model.EventDescription; import com.amazonaws.services.elasticbeanstalk.model.S3Location; import com.amazonaws.services.elasticbeanstalk.model.UpdateEnvironmentRequest; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.model.AddRoleToInstanceProfileRequest; import com.amazonaws.services.identitymanagement.model.CreateInstanceProfileRequest; import com.amazonaws.services.identitymanagement.model.CreateRoleRequest; import com.amazonaws.services.identitymanagement.model.GetInstanceProfileRequest; import com.amazonaws.services.identitymanagement.model.GetRoleRequest; import com.amazonaws.services.identitymanagement.model.InstanceProfile; import com.amazonaws.services.identitymanagement.model.PutRolePolicyRequest; import com.amazonaws.services.identitymanagement.model.Role; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.util.StringUtils; public class ElasticBeanstalkPublishingUtils { /** Duration (in milliseconds) before we give up polling for deployment status */ private static final int POLLING_TIMEOUT = 1000 * 60 * 20; /** Period (in milliseconds) between attempts to poll */ private static final int PAUSE = 1000 * 15; private final BeanstalkResourceProvider resourceProvider = new BeanstalkResourceProvider(); private final AWSElasticBeanstalk beanstalkClient; private final ElasticBeanstalkClientExtensions beanstalkClientExtensions; private final AmazonS3 s3; private final Environment environment; private final AmazonIdentityManagement iam; public ElasticBeanstalkPublishingUtils(Environment environment) { this.environment = environment; AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(environment.getAccountId()); this.beanstalkClient = clientFactory.getElasticBeanstalkClientByRegion(environment.getRegionId()); this.beanstalkClientExtensions = new ElasticBeanstalkClientExtensions(beanstalkClient); this.iam = clientFactory.getIAMClientByRegion(environment.getRegionId()); this.s3 = clientFactory.getS3ClientByRegion(environment.getRegionId()); } public void publishApplicationToElasticBeanstalk(IPath war, String versionLabel, IProgressMonitor monitor) throws CoreException { trace("Publishing application to AWS Elastic Beanstalk"); monitor.beginTask("Deploying application with AWS Elastic Beanstalk", 100); String bucketName; String applicationName = environment.getApplicationName(); String environmentName = environment.getEnvironmentName(); String key = formVersionKey(applicationName, versionLabel); checkForCancellation(monitor); long deployStartTime = System.currentTimeMillis(); try { bucketName = beanstalkClient.createStorageLocation().getS3Bucket(); if (s3.doesBucketExist(bucketName) == false) { trace("Creating Amazon S3 bucket"); monitor.setTaskName("Creating Amazon S3 bucket"); s3.createBucket(bucketName); checkForCancellation(monitor); } trace("Uploading application to Amazon S3"); monitor.setTaskName("Uploading application to Amazon S3"); long startTime = System.currentTimeMillis(); s3.putObject(bucketName, key, war.toFile()); long endTime = System.currentTimeMillis(); ElasticBeanstalkAnalytics.trackUploadMetrics(endTime - startTime, war.toFile().length()); checkForCancellation(monitor); monitor.worked(40); } catch (AmazonClientException ace) { throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to upload application to Amazon S3: " + ace.getMessage(), ace)); } try { trace("Registering new application version from " + war.toOSString()); monitor.setTaskName("Registering application version " + versionLabel); beanstalkClient.createApplicationVersion(new CreateApplicationVersionRequest() .withApplicationName(applicationName).withAutoCreateApplication(true) .withDescription(environment.getApplicationDescription()).withVersionLabel(versionLabel) .withSourceBundle(new S3Location().withS3Bucket(bucketName).withS3Key(key))); checkForCancellation(monitor); monitor.worked(40); } catch (AmazonClientException ace) { throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to register application version with AWS Elastic Beanstalk: " + ace.getMessage(), ace)); } trace("Updating environment"); monitor.setTaskName("Updating environment with latest version"); if (beanstalkClientExtensions.doesEnvironmentExist(environmentName)) { try { beanstalkClient.updateEnvironment(new UpdateEnvironmentRequest().withEnvironmentName(environmentName) .withVersionLabel(versionLabel)); } catch (AmazonClientException ace) { throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to update environment with new application version: " + ace.getMessage(), ace)); } } else { try { createNewEnvironment(versionLabel); } catch (AmazonClientException ace) { throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to create new environment: " + ace.getMessage(), ace)); } } ElasticBeanstalkAnalytics.trackDeployTotalTime(System.currentTimeMillis() - deployStartTime); trace("Done publishing to AWS Elastic Beanstalk, waiting for env to become available..."); checkForCancellation(monitor); monitor.worked(20); monitor.done(); } /** * Creates a new Elastic Beanstalk application, after checking to make sure it doesn't already * exist. * * @param applicationName * The name of the application to create. * @param description * An optional description for the new environment. */ public void createNewApplication(String applicationName, String description) { if (beanstalkClientExtensions.doesApplicationExist(applicationName)) { beanstalkClient.createApplication(new CreateApplicationRequest(applicationName) .withDescription(description)); } } /** * Returns the version label for the latest version registered for the specified application. * * @param applicationName * The name of the application whose latest version should be returned. * @return The label of the latest version registered for the specified application, or null if * no versions are registered. * @throws AmazonServiceException * If the specified application doesn't exist. */ public String getLatestApplicationVersion(String applicationName) { ApplicationVersionDescription applicationVersion = beanstalkClientExtensions .getLatestApplicationVersionDescription(applicationName); if (applicationVersion == null) { return null; } return applicationVersion.getVersionLabel(); } private static final Map<String, String> ENV_TIER_MAP; static { Map<String, String> map = new HashMap<>(); map.put(ConfigurationOptionConstants.WEB_SERVER, "Standard"); map.put(ConfigurationOptionConstants.WORKER, "SQS/HTTP"); ENV_TIER_MAP = Collections.unmodifiableMap(map); } private static final Map<String, String> ENV_TYPE_MAP; static { Map<String, String> map = new HashMap<>(); map.put(ConfigurationOptionConstants.SINGLE_INSTANCE_ENV, "SingleInstance"); map.put(ConfigurationOptionConstants.LOAD_BALANCED_ENV, "LoadBalanced"); ENV_TYPE_MAP = Collections.unmodifiableMap(map); } /** * Creates a new environment, using the specified version as the initial version to deploy. * * @param versionLabel * The initial version to deploy to the new environment. */ public void createNewEnvironment(String versionLabel) { String solutionStackName = environment.getSolutionStack(); if (solutionStackName == null) { solutionStackName = SolutionStacks.getDefaultSolutionStackName(); } CreateEnvironmentRequest request = new CreateEnvironmentRequest() .withApplicationName(environment.getApplicationName()).withSolutionStackName(solutionStackName) .withDescription(environment.getEnvironmentDescription()) .withEnvironmentName(environment.getEnvironmentName()).withVersionLabel(versionLabel); List<ConfigurationOptionSetting> optionSettings = new ArrayList<>(); if (!StringUtils.isNullOrEmpty(environment.getKeyPairName())) { optionSettings.add(new ConfigurationOptionSetting().withNamespace(ConfigurationOptionConstants.LAUNCHCONFIGURATION) .withOptionName("EC2KeyName").withValue(environment.getKeyPairName())); } if (!StringUtils.isNullOrEmpty(environment.getHealthCheckUrl())) { optionSettings.add(new ConfigurationOptionSetting().withNamespace(ConfigurationOptionConstants.APPLICATION) .withOptionName("Application Healthcheck URL").withValue(environment.getHealthCheckUrl())); } if (!StringUtils.isNullOrEmpty(environment.getSslCertificateId())) { optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.LOADBALANCER).withOptionName("SSLCertificateId") .withValue(environment.getSslCertificateId())); } if (!StringUtils.isNullOrEmpty(environment.getSnsEndpoint())) { optionSettings.add(new ConfigurationOptionSetting().withNamespace(ConfigurationOptionConstants.SNS_TOPICS) .withOptionName("Notification Endpoint").withValue(environment.getSnsEndpoint())); } if (!StringUtils.isNullOrEmpty(environment.getEnvironmentTier())) { request.setTier(new EnvironmentTier().withName(environment.getEnvironmentTier()) .withType(ENV_TIER_MAP.get(environment.getEnvironmentTier())).withVersion("1.0")); } if (!StringUtils.isNullOrEmpty(environment.getEnvironmentType())) { optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.ENVIRONMENT_TYPE).withOptionName("EnvironmentType") .withValue(ENV_TYPE_MAP.get(environment.getEnvironmentType()))); } if (!StringUtils.isNullOrEmpty(environment.getInstanceRoleName())) { if (!environment.isSkipIamRoleAndInstanceProfileCreation()) { // Create the role/instance-profile if necessary tryConfigureRoleAndInstanceProfile(); } optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.LAUNCHCONFIGURATION) .withOptionName("IamInstanceProfile").withValue(environment.getInstanceRoleName())); } if (!StringUtils.isNullOrEmpty(environment.getServiceRoleName())) { if (!environment.isSkipIamRoleAndInstanceProfileCreation() && environment.getServiceRoleName().equals(BeanstalkConstants.DEFAULT_SERVICE_ROLE_NAME)) { tryCreateDefaultServiceRoleIfNotExists(); } optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.ENVIRONMENT_TYPE).withOptionName("ServiceRole") .withValue(environment.getServiceRoleName())); if (doesSolutionStackSupportEnhancedHealth(solutionStackName)) { optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.HEALTH_REPORTING_SYSTEM) .withOptionName("SystemType").withValue("enhanced")); } } if (!StringUtils.isNullOrEmpty(environment.getVpcId())) { optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.VPC) .withOptionName("VPCId") .withValue(environment.getVpcId())); optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.VPC) .withOptionName("AssociatePublicIpAddress") .withValue(String.valueOf(environment.getAssociatePublicIpAddress()))); if (!StringUtils.isNullOrEmpty(environment.getSubnets())) { optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.VPC) .withOptionName("Subnets") .withValue(environment.getSubnets())); } if (!StringUtils.isNullOrEmpty(environment.getElbSubnets())) { optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.VPC) .withOptionName("ELBSubnets") .withValue(environment.getElbSubnets())); } if (!StringUtils.isNullOrEmpty(environment.getElbScheme()) && BeanstalkConstants.ELB_SCHEME_INTERNAL.equals(environment.getElbScheme())) { optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.VPC) .withOptionName("ELBScheme") .withValue(environment.getElbScheme())); } if (!StringUtils.isNullOrEmpty(environment.getSecurityGroup())) { optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.LAUNCHCONFIGURATION) .withOptionName("SecurityGroups") .withValue(environment.getSecurityGroup())); } } if (StringUtils.isNullOrEmpty(environment.getWorkerQueueUrl())) { optionSettings.add(new ConfigurationOptionSetting() .withNamespace(ConfigurationOptionConstants.SQSD) .withOptionName("WorkerQueueURL") .withValue(environment.getWorkerQueueUrl())); } if (optionSettings.size() > 0) { request.setOptionSettings(optionSettings); } if (!StringUtils.isNullOrEmpty(environment.getCname())) { request.setCNAMEPrefix(environment.getCname()); } beanstalkClient.createEnvironment(request); } private boolean doesSolutionStackSupportEnhancedHealth(String solutionStackName) { return !solutionStackName.contains("Tomcat 6"); } private void tryCreateDefaultServiceRoleIfNotExists() { try { String permissionsPolicy = resourceProvider.getServiceRolePermissionsPolicy().asString(); String trustPolicy = resourceProvider.getServiceRoleTrustPolicy().asString(); createRoleIfNotExists(BeanstalkConstants.DEFAULT_SERVICE_ROLE_NAME, permissionsPolicy, trustPolicy); } catch (Exception e) { Status status = new Status(Status.WARNING, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to create default service role. " + "Proceeding with deployment under the assumption it already exists", e); StatusManager.getManager().handle(status, StatusManager.LOG); } } private void createRoleIfNotExists(String roleName, String permissionsPolicy, String trustPolicy) { if (!doesRoleExist(roleName)) { iam.createRole(new CreateRoleRequest().withRoleName(roleName).withPath("/") .withAssumeRolePolicyDocument(trustPolicy)); iam.putRolePolicy(new PutRolePolicyRequest().withRoleName(roleName) .withPolicyName("DefaultAccessPolicy-" + roleName).withPolicyDocument(permissionsPolicy)); } } private boolean doesRoleExist(String roleName) { return getRole(BeanstalkConstants.DEFAULT_SERVICE_ROLE_NAME) != null; } private void tryConfigureRoleAndInstanceProfile() { try { configureRoleAndInstanceProfile(); } catch (Exception e) { Status status = new Status(Status.WARNING, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to create default instance role or instance profile. " + "Proceeding with deployment under the assumption they already exist.", e); StatusManager.getManager().handle(status, StatusManager.LOG); } } private void configureRoleAndInstanceProfile() { String roleName = environment.getInstanceRoleName(); if (BeanstalkConstants.DEFAULT_INSTANCE_ROLE_NAME.equals(roleName)) { String permissionsPolicy = resourceProvider.getInstanceProfilePermissionsPolicy().asString(); String trustPolicy = resourceProvider.getInstanceProfileTrustPolicy().asString(); createRoleIfNotExists(BeanstalkConstants.DEFAULT_INSTANCE_ROLE_NAME, permissionsPolicy, trustPolicy); } String instanceProfileName = roleName; // The console automatically creates an instance profile with the same name when you create // an EC2 IAM role. If no instance profile exists then the user most likely created the role // through the API so we create the instance profile on their behalf InstanceProfile instanceProfile = createInstanceProfileIfNotExists(instanceProfileName); // If an instance profile that has the same name as the role exists but doesn't have that // role attached then add it here. This can really only happen if the user is creating the // role and instance profile separately through the // API if (!isRoleAddedToInstanceProfile(roleName, instanceProfile)) { iam.addRoleToInstanceProfile(new AddRoleToInstanceProfileRequest().withInstanceProfileName( instanceProfileName).withRoleName(roleName)); } } /** * Create the instance profile with the specified name or return it if it already exists. * * @param instanceProfileName * @return InstanceProfile object of either the existing instance profile or the newly created * one */ private InstanceProfile createInstanceProfileIfNotExists(String instanceProfileName) { InstanceProfile instanceProfile = getInstanceProfile(instanceProfileName); if (instanceProfile == null) { instanceProfile = iam.createInstanceProfile( new CreateInstanceProfileRequest().withInstanceProfileName(instanceProfileName).withPath("/")) .getInstanceProfile(); } return instanceProfile; } private InstanceProfile getInstanceProfile(String profileName) throws AmazonClientException { try { return iam.getInstanceProfile(new GetInstanceProfileRequest().withInstanceProfileName(profileName)) .getInstanceProfile(); } catch (AmazonServiceException ase) { if (ase.getErrorCode().equals("NoSuchEntity")) { return null; } throw ase; } } private Role getRole(String roleName) throws AmazonClientException { try { return iam.getRole(new GetRoleRequest().withRoleName(roleName)).getRole(); } catch (AmazonServiceException ase) { if (ase.getErrorCode().equals("NoSuchEntity")) { return null; } throw ase; } } private boolean isRoleAddedToInstanceProfile(String roleName, InstanceProfile instanceProfile) { for (Role role : instanceProfile.getRoles()) { if (role.getRoleName().equals(roleName)) { return true; } } return false; } public void waitForEnvironmentToBecomeAvailable(IModule moduleToPublish, IProgressMonitor monitor, Runnable runnable) throws CoreException { int errorCount = 0; long startTime = System.currentTimeMillis(); Date eventStartTime = new Date(startTime - (1000 * 60 * 30)); String applicationName = environment.getApplicationName(); String environmentName = environment.getEnvironmentName(); boolean launchingNewEnvironment = isLaunchingNewEnvironment(environmentName); monitor.beginTask("Waiting for environment to become available", POLLING_TIMEOUT); monitor.setTaskName("Waiting for environment to become available"); while (System.currentTimeMillis() - startTime < POLLING_TIMEOUT) { List<EventDescription> events = beanstalkClient.describeEvents( new DescribeEventsRequest().withEnvironmentName(environmentName).withStartTime(eventStartTime)) .getEvents(); if (events.size() > 0) { String status = "Latest Event: " + events.get(0).getMessage(); if (launchingNewEnvironment) { status += " (Note: Launching a new environment may take several minutes)"; } else { status += " (Note: Updating an environment may take several minutes)"; } monitor.setTaskName(status); } try { Thread.sleep(PAUSE); } catch (Exception e) { } if (monitor.isCanceled()) { return; } if (runnable != null) { try { runnable.run(); } catch (Exception e) { Status status = new Status(Status.INFO, ElasticBeanstalkPlugin.PLUGIN_ID, e.getMessage(), e); StatusManager.getManager().handle(status, StatusManager.LOG); } } try { trace("Polling environment for status..."); EnvironmentDescription environmentDesc = beanstalkClientExtensions .getEnvironmentDescription(environmentName); if (environmentDesc != null) { trace(" - " + environmentDesc.getStatus()); EnvironmentStatus environmentStatus = null; try { environmentStatus = EnvironmentStatus.fromValue(environmentDesc.getStatus()); } catch (IllegalArgumentException e) { Status status = new Status(Status.INFO, ElasticBeanstalkPlugin.PLUGIN_ID, "Unknown environment status: " + environmentDesc.getStatus()); StatusManager.getManager().handle(status, StatusManager.LOG); continue; } switch (environmentStatus) { case Ready: trace(" - Health: " + environmentDesc.getHealth()); if (EnvironmentHealth.Green.toString().equalsIgnoreCase(environmentDesc.getHealth())) { trace("**Server started**"); Status status = new Status(Status.INFO, ElasticBeanstalkPlugin.PLUGIN_ID, "Deployed application '" + applicationName + "' " + "to environment '" + environmentName + "' " + "\nApplication available at: " + environmentDesc.getCNAME()); StatusManager.getManager().handle(status, StatusManager.LOG); return; } break; case Terminated: case Terminating: throw new CoreException(new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Environment failed to deploy. Check environment events for more details.")); } } // reset error count so that we only count consecutive errors errorCount = 0; } catch (AmazonClientException ace) { if (errorCount++ > 4) { throw new CoreException(new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to detect application deployment: " + ace.getMessage(), ace)); } } } throw new CoreException(new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to detect application deployment")); } private void checkForCancellation(IProgressMonitor monitor) throws CoreException { if (monitor.isCanceled()) { throw new CoreException(new Status(Status.CANCEL, ElasticBeanstalkPlugin.PLUGIN_ID, "Canceled")); } } private boolean isLaunchingNewEnvironment(String environmentName) { EnvironmentDescription environmentDesc = beanstalkClientExtensions.getEnvironmentDescription(environmentName); if (environmentDesc == null) { return true; } return environmentDesc.getStatus().equals(EnvironmentStatus.Launching.toString()); } /** * Returns the key under which to store an uploaded application version. */ private String formVersionKey(String applicationName, String versionLabel) { try { return URLEncoder.encode(applicationName + "-" + versionLabel + ".war", "UTF-8"); } catch (UnsupportedEncodingException e) { return applicationName + "-" + versionLabel + ".war"; } } }
7,345
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/EnvironmentBehavior.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import static com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin.trace; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.eclipse.core.runtime.CoreException; 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.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.statushandlers.StatusManager; import org.eclipse.wst.server.core.IModule; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.model.ServerBehaviourDelegate; import org.eclipse.wst.server.core.model.ServerDelegate; import com.amazonaws.eclipse.elasticbeanstalk.deploy.WTPWarUtils; import com.amazonaws.eclipse.elasticbeanstalk.jobs.RestartEnvironmentJob; import com.amazonaws.eclipse.elasticbeanstalk.jobs.TerminateEnvironmentJob; import com.amazonaws.eclipse.elasticbeanstalk.jobs.UpdateEnvironmentJob; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationSettingsDescription; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentStatus; import com.amazonaws.services.elasticbeanstalk.model.UpdateEnvironmentRequest; public class EnvironmentBehavior extends ServerBehaviourDelegate { /** The latest status of this environment, as reported from AWS Elastic Beanstalk. */ private EnvironmentStatus latestEnvironmentStatus; @Override public void setupLaunchConfiguration(ILaunchConfigurationWorkingCopy workingCopy, IProgressMonitor monitor) throws CoreException { trace("setupLaunchConfiguration(launchConfig: " + workingCopy+ ", environment: " + getEnvironment().getEnvironmentName() + ")"); super.setupLaunchConfiguration(workingCopy, monitor); } /** * The current job to update an AWS Elastic Beanstalk environment. We set up the * job as part of the WTP publishing process, then schedule it at the end of * publishing. */ private UpdateEnvironmentJob currentUpdateEnvironmentJob; /** * Dialog to collect deployment information */ private DeploymentInformationDialog deploymentInformationDialog; private static final IStatus ERROR_STATUS = new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Environment is not ready"); @Override public void stop(boolean force) { trace("Stopping (force:" + force + ")"); setServerState(IServer.STATE_STOPPING); new TerminateEnvironmentJob(getEnvironment()).schedule(); } @Override public void restart(String launchMode) throws CoreException { trace("Restarting(launchMode: " + launchMode + ", environment: " + getEnvironment().getEnvironmentName()); setServerState(IServer.STATE_STARTING); if ( getServer().getMode().equals(launchMode) ) { new RestartEnvironmentJob(getEnvironment()).schedule(); } else if ( launchMode.equals(ILaunchManager.DEBUG_MODE) ) { enableDebugging(); trace("Adding a debug port for environment " + getEnvironment().getEnvironmentName()); } ElasticBeanstalkPlugin.getDefault().syncEnvironments(); } @Override protected void publishStart(IProgressMonitor monitor) throws CoreException { trace("PublishStart: " + getEnvironment().getEnvironmentName()); currentUpdateEnvironmentJob = new UpdateEnvironmentJob(getEnvironment(), getServer()); } @Override protected void publishModule(int publishKind, int deltaKind, IModule[] moduleTree, IProgressMonitor monitor) throws CoreException { trace("PublishModule:" + " (publishKind: " + WtpConstantsUtils.lookupPublishKind(publishKind) + " deltaKind: " + WtpConstantsUtils.lookupDeltaKind(deltaKind) + " moduleTree: " + Arrays.asList(moduleTree) + ")"); // Ignore automatic publishes if (publishKind == IServer.PUBLISH_AUTO) return; // If the module doesn't need any publishing, and we don't need a full publish, don't do anything if (publishKind == IServer.PUBLISH_INCREMENTAL && deltaKind == NO_CHANGE) return; // If we're just removing a module, we don't need to do anything if (deltaKind == REMOVED) return; // TODO: If we can ask the job what module its uploading, we can check and not export twice IPath exportedWar = WTPWarUtils.exportProjectToWar(moduleTree[0].getProject(), getTempDirectory()); monitor.worked(100); trace("Created war: " + exportedWar.toOSString()); currentUpdateEnvironmentJob.setModuleToPublish(moduleTree[0], exportedWar); updateModuleState(moduleTree[0], IServer.STATE_STARTING, IServer.PUBLISH_STATE_NONE); } @Override protected void publishFinish(IProgressMonitor monitor) throws CoreException { trace("PublishFinish(" + getEnvironment().getEnvironmentName() + ")"); try { if ( currentUpdateEnvironmentJob.needsToDeployNewVersion() ) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { Shell shell = Display.getDefault().getActiveShell(); if ( shell == null ) shell = Display.getDefault().getShells()[0]; /* * Use the deployment dialog from earlier, if we have * one. Otherwise create a new one. */ if ( deploymentInformationDialog == null ) { final List<ConfigurationSettingsDescription> settings = getEnvironment().getCurrentSettings(); String debugPort = Environment.getDebugPort(settings); String securityGroup = Environment.getSecurityGroup(settings); boolean confirmIngress = false; if ( debugPort != null && securityGroup != null && !getEnvironment().isIngressAllowed(debugPort, settings) ) { confirmIngress = true; } boolean letUserSelectVersionLabel = !getEnvironment().getIncrementalDeployment(); if (letUserSelectVersionLabel || confirmIngress) { deploymentInformationDialog = new DeploymentInformationDialog(shell, getEnvironment(), getServer().getMode(), letUserSelectVersionLabel, false, confirmIngress); deploymentInformationDialog.open(); if ( deploymentInformationDialog.getReturnCode() != MessageDialog.OK ) return; // Allow ingress on their security group if necessary if ( confirmIngress ) getEnvironment().openSecurityGroupPort(debugPort, securityGroup); } } if (deploymentInformationDialog != null) { currentUpdateEnvironmentJob.setVersionLabel(deploymentInformationDialog.getVersionLabel()); currentUpdateEnvironmentJob.setDebugInstanceId(deploymentInformationDialog.getDebugInstanceId()); } setServerState(IServer.STATE_STARTING); currentUpdateEnvironmentJob.schedule(); } }); if ( deploymentInformationDialog != null && deploymentInformationDialog.getReturnCode() != MessageDialog.OK ) { updateModuleState(currentUpdateEnvironmentJob.getModuleToPublish(), IServer.STATE_UNKNOWN, IServer.PUBLISH_STATE_UNKNOWN); throw new CoreException(new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Publish canceled")); } } } finally { currentUpdateEnvironmentJob = null; deploymentInformationDialog = null; } } private int translateStatus(EnvironmentStatus status) { if (status == null) return IServer.STATE_STOPPED; switch (status) { case Launching: case Updating: return IServer.STATE_STARTING; case Ready: return IServer.STATE_STARTED; case Terminated: return IServer.STATE_STOPPED; case Terminating: return IServer.STATE_STOPPING; default: return IServer.STATE_UNKNOWN; } } @Override public IStatus canRestart(String mode) { trace("canRestart(launchMode: " + mode + ", environment: " + getEnvironment().getEnvironmentName() + ")"); if (latestEnvironmentStatus == null) return ERROR_STATUS; return super.canRestart(mode); } @Override public IStatus canStop() { trace("canStop(environment: " + getEnvironment().getEnvironmentName() + ")"); if (latestEnvironmentStatus == null) return ERROR_STATUS; return super.canStop(); } @Override public IStatus canStart(String launchMode) { trace("canStart(launchMode: " + launchMode + ", environment: " + getEnvironment().getEnvironmentName() + ")"); // Don't allow the user to start the server if no projects are added yet if (getServer().getModules().length == 0) return ERROR_STATUS; if (latestEnvironmentStatus == null) return super.canStart(launchMode); if (latestEnvironmentStatus == EnvironmentStatus.Launching || latestEnvironmentStatus == EnvironmentStatus.Updating || latestEnvironmentStatus == EnvironmentStatus.Terminating) { return ERROR_STATUS; } return super.canStart(launchMode); } @Override public IStatus canPublish() { trace("canPublish(environment: " + getEnvironment().getEnvironmentName() + ")"); // Don't allow the user to publish to the server if no projects are added yet if (getServer().getModules().length == 0) return ERROR_STATUS; if (latestEnvironmentStatus == null) return super.canPublish(); if (latestEnvironmentStatus == EnvironmentStatus.Launching || latestEnvironmentStatus == EnvironmentStatus.Updating || latestEnvironmentStatus == EnvironmentStatus.Terminating) { return ERROR_STATUS; } return super.canPublish(); } public void updateServer(EnvironmentDescription environmentDescription, List<ConfigurationSettingsDescription> settings) { trace("Updating server with latest AWS Elastic Beanstalk environment description (server: " + getServer().getName() + ")"); if (environmentDescription == null) { latestEnvironmentStatus = null; } else { try { latestEnvironmentStatus = EnvironmentStatus.fromValue(environmentDescription.getStatus()); } catch (IllegalArgumentException e) { Status status = new Status(Status.INFO, ElasticBeanstalkPlugin.PLUGIN_ID, "Unknown environment status: " + environmentDescription.getStatus()); StatusManager.getManager().handle(status, StatusManager.LOG); } setServerStatus(new Status(Status.WARNING, ElasticBeanstalkPlugin.PLUGIN_ID, environmentDescription.getSolutionStackName() + " : " + environmentDescription.getStatus())); if ( settings != null ) { String debugPort = Environment.getDebugPort(settings); if ( debugPort != null ) setMode(ILaunchManager.DEBUG_MODE); else setMode(ILaunchManager.RUN_MODE); } } setServerState(translateStatus(latestEnvironmentStatus)); getEnvironment().setCachedEnvironmentDescription(environmentDescription); for (IModule module : getServer().getModules()) { setModuleStatus(new IModule[] {module}, new Status(IStatus.OK, ElasticBeanstalkPlugin.PLUGIN_ID, getEnvironment().getApplicationName())); } } protected Environment getEnvironment() { return (Environment)getServer().loadAdapter(ServerDelegate.class, null); } // This is called by our ElasticBeanstalkLaunchConfigurationDelegate, but only when // the server is moving from stopped -> starting (if we have that flag set in plugin.xml). public void setupLaunch(ILaunch launch, String launchMode, IProgressMonitor monitor) throws CoreException { trace("EnvironmentBehavior:setupLaunch(" + launch + ", " + launchMode + ")"); setServerRestartState(false); setServerState(IServer.STATE_STARTING); setMode(launchMode); setServerState(IServer.STATE_STARTED); } public void updateServerState(int state) { setServerState(state); } public void updateModuleState(IModule module, int moduleState, int modulePublishState) { setModuleState(new IModule[] {module}, moduleState); setModulePublishState(new IModule[] {module}, modulePublishState); for (IModule module2 : getEnvironment().getChildModules(new IModule[] {module})) { setModuleState(new IModule[] {module, module2}, moduleState); setModulePublishState(new IModule[] {module, module2}, modulePublishState); } } /** * Enables debugging on a port the user chooses. */ public void enableDebugging() { final List<ConfigurationSettingsDescription> settings = getEnvironment().getCurrentSettings(); ConfigurationOptionSetting opt = Environment.getJVMOptions(settings); if ( opt == null ) { opt = new ConfigurationOptionSetting().withNamespace(ConfigurationOptionConstants.JVMOPTIONS) .withOptionName("JVM Options"); } String currentOptions = opt.getValue(); if ( currentOptions == null ) { currentOptions = ""; } if ( !currentOptions.contains("-Xdebug") ) { currentOptions += " " + "-Xdebug"; } if ( !currentOptions.contains("-Xrunjdwp:") ) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { // Incremental deployments are automatically assigned version labels boolean letUserSelectVersionLabel = !getEnvironment().getIncrementalDeployment(); deploymentInformationDialog = new DeploymentInformationDialog(Display.getDefault().getActiveShell(), getEnvironment(), ILaunchManager.DEBUG_MODE, letUserSelectVersionLabel, true, true); deploymentInformationDialog.open(); } }); int result = deploymentInformationDialog.getReturnCode(); if ( result == Dialog.OK ) { String debugPort = deploymentInformationDialog.getDebugPort(); currentOptions += " " + "-Xrunjdwp:transport=dt_socket,address=" + debugPort + ",server=y,suspend=n"; } else { deploymentInformationDialog = null; setServerState(IServer.STATE_UNKNOWN); ElasticBeanstalkPlugin.getDefault().syncEnvironments(); throw new RuntimeException("Operation canceled"); } } else { deploymentInformationDialog = null; throw new RuntimeException("Environment JVM options already contains -Xrunjdwp argument, " + "but we were unable to determine the remote debugging port"); } opt.setValue(currentOptions); UpdateEnvironmentRequest rq = new UpdateEnvironmentRequest(); rq.setEnvironmentName(getEnvironment().getEnvironmentName()); Collection<ConfigurationOptionSetting> outgoingSettings = new ArrayList<>(); outgoingSettings.add(opt); rq.setOptionSettings(outgoingSettings); getEnvironment().getClient().updateEnvironment(rq); if ( !getEnvironment().isIngressAllowed(deploymentInformationDialog.getDebugPort(), settings) ) { getEnvironment().openSecurityGroupPort(deploymentInformationDialog.getDebugPort(), Environment.getSecurityGroup(settings)); } } }
7,346
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/BasicRuntime.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import org.eclipse.wst.server.core.model.RuntimeDelegate; public class BasicRuntime extends RuntimeDelegate { public BasicRuntime() {} }
7,347
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/DeploymentInformationDialog.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.elasticbeanstalk; import java.util.List; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.amazonaws.AmazonServiceException; import com.amazonaws.eclipse.core.AwsToolkitCore; /** * Dialog to collect information about a deployment prior to its creation. */ public class DeploymentInformationDialog extends MessageDialog { private final boolean enableDebugging; private final boolean warnAboutIngress; private final boolean showVersionTextBox; private final Environment environment; private final String launchMode; private Text debugPortText; private String debugPort = ""; private String debugInstanceId = ""; private String versionLabel = ""; String getDebugInstanceId() { return debugInstanceId; } String getVersionLabel() { return versionLabel; } String getDebugPort() { return debugPort; } public DeploymentInformationDialog(Shell parentShell, Environment environment, String launchMode, boolean showVersionLabelTextBox, boolean enableDebugging, boolean warnAboutIngress) { super(parentShell, "Publishing to AWS Elastic Beanstalk", AwsToolkitCore.getDefault().getImageRegistry() .get(AwsToolkitCore.IMAGE_AWS_ICON), "Configure your environment deployment options", MessageDialog.NONE, new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0); this.showVersionTextBox = showVersionLabelTextBox; this.enableDebugging = enableDebugging; this.warnAboutIngress = warnAboutIngress; this.environment = environment; this.launchMode = launchMode; this.versionLabel = "v" + System.currentTimeMillis(); } @Override protected Control createCustomArea(Composite parent) { Composite composite = parent; GridLayout layout = new GridLayout(2, false); layout.marginWidth = 0; composite.setLayout(layout); if ( showVersionTextBox ) createVersionTextBox(composite); if ( enableDebugging ) createDebugPortTextBox(parent); if ( launchMode.equals(ILaunchManager.DEBUG_MODE) ) createInstanceSelectionCombo(parent); if ( warnAboutIngress ) createIngressWarning(parent); createDurationLabel(composite); composite.pack(true); return composite; } /** * Creates a combo selection box to choose which EC2 instance to connect to, * if there's more than one. */ private void createInstanceSelectionCombo(Composite parent) { try { final List<String> ec2InstanceIds = environment.getEC2InstanceIds(); if ( ec2InstanceIds.size() < 2 ) { return; } debugInstanceId = ec2InstanceIds.get(0); Label label = new Label(parent, SWT.None); label.setText("Connect remote debugger to instance: "); final Combo combo = new Combo(parent, SWT.READ_ONLY); combo.setItems(ec2InstanceIds.toArray(new String[ec2InstanceIds.size()])); combo.select(0); combo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { debugInstanceId = ec2InstanceIds.get(combo.getSelectionIndex()); } }); GridDataFactory.fillDefaults().grab(true, false).applyTo(combo); } catch (AmazonServiceException ignored) { return; } } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); validate(); } private void validate() { if ( versionLabel.length() == 0 ) { getButton(0).setEnabled(false); return; } if ( enableDebugging ) { if ( debugPort.length() == 0 ) { getButton(0).setEnabled(false); return; } try { Integer.parseInt(debugPort); } catch ( NumberFormatException e ) { getButton(0).setEnabled(false); } } getButton(0).setEnabled(true); } private void createVersionTextBox(Composite composite) { Label versionLabelLabel = new Label(composite, SWT.NONE); versionLabelLabel.setText("Version Label:"); final Text versionLabelText = new Text(composite, SWT.BORDER); versionLabelText.setText(versionLabel); versionLabelText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true)); versionLabelText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { versionLabel = versionLabelText.getText(); validate(); } }); } private void createDebugPortTextBox(Composite parent) { Label chooseADebugPort = new Label(parent, SWT.READ_ONLY); chooseADebugPort.setText("Remote debugging port:"); debugPortText = new Text(parent, SWT.BORDER); debugPortText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { debugPort = debugPortText.getText(); validate(); } }); } private void createIngressWarning(Composite parent) { Label ingressWarning = new Label(parent, SWT.READ_ONLY | SWT.WRAP); ingressWarning.setText("Please note: to connect the remote debugger, " + "the debug port will be opened for TCP ingress " + "on your EC2 security group."); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.TOP).span(2, 1).applyTo(ingressWarning); } private void createDurationLabel(Composite composite) { final Label info = new Label(composite, SWT.READ_ONLY | SWT.WRAP); info.setText("Launching a new environment may take several minutes. " + "To monitor its progress, check the Progress View."); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, true); gridData.horizontalSpan = 2; gridData.widthHint = 300; info.setLayoutData(gridData); } }
7,348
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ElasticBeanstalkAnalytics.java
/* * Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.ToolkitAnalyticsManager; import com.amazonaws.eclipse.core.telemetry.ToolkitAnalyticsUtils; public final class ElasticBeanstalkAnalytics { /* * Deploy Application to Elastic Beanstalk */ private static final String EVENT_TYPE_DEPLOY_APPLICATION = "beanstalk_deployApplication"; private static final String METRIC_NAME_DEPLOY_TOTAL_TIME_MS = "DeployTotalTimeMs"; private static final String METRIC_NAME_UPLOAD_S3_BUCKET_TIME_MS = "UploadS3BucketTimeMs"; private static final String METRIC_NAME_UPLOAD_S3_BUCKET_BYTES_PER_MS = "UploadS3BucketBytesPerMs"; private static final String METRIC_NAME_APPLICATION_SOURCE_BUNDLE_SIZE = "ApplicationSourceBundleSize"; /* * Create New project for Eclipse Beanstalk */ private static final String EVENT_TYPE_CREATE_NEW_WEB_APPLICATION = "beanstalk_createApplication"; private static final String ATTRI_NAME_WEB_APPLICATION_TYPE = "ApplicationType"; private static final String ATTRI_VALUE_WEB_APPLICATION_DDB = "WebApplication-DDB"; private static final String ATTRI_VALUE_WEB_APPLICATION_NDDB = "WebApplication-NDDB"; private static final String ATTRI_VALUE_WORKER_APPLICATION = "WorkerApplication"; private static final ToolkitAnalyticsManager ANALYTICS = AwsToolkitCore.getDefault().getAnalyticsManager(); /* * Analytics for ElasticBeanstalk-DeployApplication */ public static void trackDeployTotalTime(long deployTotalTime) { ANALYTICS.publishEvent(ANALYTICS.eventBuilder() .setEventType(EVENT_TYPE_DEPLOY_APPLICATION) .addMetric(METRIC_NAME_DEPLOY_TOTAL_TIME_MS, deployTotalTime) .build()); } public static void trackUploadMetrics(long uploadS3BucketTime, long sourceFileBundleSize) { ToolkitAnalyticsUtils.trackSpeedMetrics(ANALYTICS, EVENT_TYPE_DEPLOY_APPLICATION, METRIC_NAME_UPLOAD_S3_BUCKET_TIME_MS, uploadS3BucketTime, METRIC_NAME_APPLICATION_SOURCE_BUNDLE_SIZE, sourceFileBundleSize, METRIC_NAME_UPLOAD_S3_BUCKET_BYTES_PER_MS); } /* * Analytics for ElasticBeanstalk-CreateNewProject */ public static void trackCreateNewWebApplication_DDB() { ANALYTICS.publishEvent(ANALYTICS.eventBuilder() .setEventType(EVENT_TYPE_CREATE_NEW_WEB_APPLICATION) .addAttribute(ATTRI_NAME_WEB_APPLICATION_TYPE, ATTRI_VALUE_WEB_APPLICATION_DDB) .build()); } public static void trackCreateNewWebApplication_NDDB() { ANALYTICS.publishEvent(ANALYTICS.eventBuilder() .setEventType(EVENT_TYPE_CREATE_NEW_WEB_APPLICATION) .addAttribute(ATTRI_NAME_WEB_APPLICATION_TYPE, ATTRI_VALUE_WEB_APPLICATION_NDDB) .build()); } public static void trackCreateNewWorkerApplication() { ANALYTICS.publishEvent(ANALYTICS.eventBuilder() .setEventType(EVENT_TYPE_CREATE_NEW_WEB_APPLICATION) .addAttribute(ATTRI_NAME_WEB_APPLICATION_TYPE, ATTRI_VALUE_WORKER_APPLICATION) .build()); } }
7,349
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ElasticBeanstalkPlugin.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IStartup; import org.eclipse.wst.server.core.IRuntimeWorkingCopy; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.IServerLifecycleListener; import org.eclipse.wst.server.core.IServerType; import org.eclipse.wst.server.core.IServerWorkingCopy; import org.eclipse.wst.server.core.ServerCore; import org.osgi.framework.BundleContext; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.elasticbeanstalk.jobs.SyncEnvironmentsJob; import com.amazonaws.eclipse.elasticbeanstalk.server.ui.ServerDefaultsUtils; import com.amazonaws.eclipse.elasticbeanstalk.solutionstacks.SolutionStacks; import com.amazonaws.eclipse.elasticbeanstalk.util.ElasticBeanstalkClientExtensions; import com.amazonaws.services.elasticbeanstalk.model.ApplicationDescription; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationSettingsDescription; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; /** * The activator class controls the plug-in life cycle */ public class ElasticBeanstalkPlugin extends AbstractAwsPlugin implements IStartup { public static final String IMG_AWS_BOX = "aws-box"; public static final String IMG_SERVER = "server"; public static final String IMG_IMPORT = "import"; public static final String IMG_EXPORT = "export"; public static final String IMG_CLIPBOARD = "clipboard"; public static final String IMG_ENVIRONMENT = "environment"; public static final String IMG_SERVICE = "beanstalk-service"; public static final String IMG_APPLICATION = "application"; private static final String SUBTLE_DIALOG_FONT = "subtle-dialog"; public static final String PLUGIN_ID = "com.amazonaws.eclipse.elasticbeanstalk"; //$NON-NLS-1$ public static final String DEFAULT_REGION = "us-east-1"; // The shared instance private static ElasticBeanstalkPlugin plugin; private SyncEnvironmentsJob syncEnvironmentsJob; private NewServerListener newServerListener; public static final String TOMCAT_6_SERVER_TYPE_ID = "com.amazonaws.eclipse.elasticbeanstalk.servers.environment"; //$NON-NLS-1$ public static final String TOMCAT_7_SERVER_TYPE_ID = "com.amazonaws.eclipse.elasticbeanstalk.servers.tomcat7"; //$NON-NLS-1$ public static final String TOMCAT_8_SERVER_TYPE_ID = "com.amazonaws.eclipse.elasticbeanstalk.servers.tomcat8"; //$NON-NLS-1$ public static final Collection<String> SERVER_TYPE_IDS = new HashSet<>(); private Font subtleDialogFont; static { SERVER_TYPE_IDS.add(TOMCAT_6_SERVER_TYPE_ID); SERVER_TYPE_IDS.add(TOMCAT_7_SERVER_TYPE_ID); SERVER_TYPE_IDS.add(TOMCAT_8_SERVER_TYPE_ID); } /** * Returns the shared plugin instance. * * @return the shared plugin instance. */ public static ElasticBeanstalkPlugin getDefault() { return plugin; } public static void trace(String message) { if ( Platform.inDebugMode() ) System.out.println(message); } @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; syncEnvironmentsJob = new SyncEnvironmentsJob(); syncEnvironmentsJob.schedule(); newServerListener = new NewServerListener(); ServerCore.addServerLifecycleListener(newServerListener); } /* * (non-Javadoc) * * @see * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext * ) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; syncEnvironmentsJob.cancel(); ServerCore.removeServerLifecycleListener(newServerListener); super.stop(context); if (subtleDialogFont != null) subtleDialogFont.dispose(); subtleDialogFont = null; } /* (non-Javadoc) * @see org.eclipse.ui.IStartup#earlyStartup() */ @Override public void earlyStartup() { } public void syncEnvironments() { if ( syncEnvironmentsJob != null ) syncEnvironmentsJob.wakeUp(); } @Override protected ImageRegistry createImageRegistry() { ImageRegistry imageRegistry = new ImageRegistry(Display.getCurrent()); imageRegistry.put(IMG_EXPORT, ImageDescriptor.createFromFile(getClass(), "/icons/export.gif")); imageRegistry.put(IMG_IMPORT, ImageDescriptor.createFromFile(getClass(), "/icons/import.gif")); imageRegistry.put(IMG_SERVER, ImageDescriptor.createFromFile(getClass(), "/icons/server.png")); imageRegistry.put(IMG_AWS_BOX, ImageDescriptor.createFromFile(getClass(), "/icons/aws-box.gif")); imageRegistry.put(IMG_CLIPBOARD, ImageDescriptor.createFromFile(getClass(), "/icons/clipboard.gif")); imageRegistry.put(IMG_ENVIRONMENT, ImageDescriptor.createFromFile(getClass(), "/icons/environment.png")); imageRegistry.put(IMG_SERVICE, ImageDescriptor.createFromFile(getClass(), "/icons/beanstalk-service.png")); imageRegistry.put(IMG_APPLICATION, ImageDescriptor.createFromFile(getClass(), "/icons/application.png")); return imageRegistry; } public Font getSubtleDialogFont() { return subtleDialogFont; } public void initializeSubtleDialogFont(Font baseFont) { if (getSubtleDialogFont() != null) return; FontData[] fontData = baseFont.getFontData(); for (FontData fd : fontData) fd.setStyle(SWT.ITALIC); subtleDialogFont = new Font(Display.getDefault(), fontData); } /** * Returns all AWS Elastic Beanstalk servers known to ServerCore. */ public static Collection<IServer> getExistingElasticBeanstalkServers() { List<IServer> elasticBeanstalkServers = new ArrayList<>(); IServer[] servers = ServerCore.getServers(); for ( IServer server : servers ) { if ( server.getServerType() == null) continue; if ( SERVER_TYPE_IDS.contains(server.getServerType().getId()) ) { elasticBeanstalkServers.add(server); } } return elasticBeanstalkServers; } /** * Returns the server matching the description given in the region given, if * it can be found, or null otherwise. */ public static IServer getServer(EnvironmentDescription environmentDescription, Region region) { for ( IServer server : getExistingElasticBeanstalkServers() ) { if ( environmentsSame(environmentDescription, region, server) ) { return server; } } return null; } /** * Returns whether the environment given represents the server given. */ public static boolean environmentsSame(EnvironmentDescription env, Region region, IServer server) { String beanstalkEndpoint = region.getServiceEndpoints().get(ServiceAbbreviations.BEANSTALK); Environment environment = (Environment) server.getAdapter(Environment.class); if (environment == null) return false; return environment.getApplicationName().equals(env.getApplicationName()) && environment.getEnvironmentName().equals(env.getEnvironmentName()) && environment.getRegionEndpoint().equals(beanstalkEndpoint); } /** * Imports an environment as a Server and returns it. * * @param monitor * An optional progress monitor that will perform 3 units of work * during the import process. * @throws CoreException * If the environment cannot be imported */ public static IServer importEnvironment(EnvironmentDescription environmentDescription, Region region, IProgressMonitor monitor) throws CoreException { String solutionStackName = environmentDescription.getSolutionStackName(); String serverTypeId = null; try { serverTypeId = SolutionStacks.lookupServerTypeIdBySolutionStack(solutionStackName); } catch ( Exception e ) { throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, e.getMessage())); } final IServerType serverType = ServerCore.findServerType(serverTypeId); IRuntimeWorkingCopy runtime = serverType.getRuntimeType().createRuntime(null, monitor); IServerWorkingCopy serverWorkingCopy = serverType.createServer(null, null, runtime, monitor); ServerDefaultsUtils.setDefaultHostName(serverWorkingCopy, region.getServiceEndpoints().get(ServiceAbbreviations.BEANSTALK)); ServerDefaultsUtils.setDefaultServerName(serverWorkingCopy, environmentDescription.getEnvironmentName()); /* * These values must be bootstrapped before we can ask the environment * about its configuration. */ Environment env = (Environment) serverWorkingCopy.loadAdapter(Environment.class, monitor); env.setAccountId(AwsToolkitCore.getDefault().getCurrentAccountId()); env.setRegionId(region.getId()); env.setApplicationName(environmentDescription.getApplicationName()); env.setEnvironmentName(environmentDescription.getEnvironmentName()); env.setIncrementalDeployment(true); fillInEnvironmentValues(environmentDescription, env, monitor); monitor.subTask("Creating server"); IServer server = serverWorkingCopy.save(true, monitor); runtime.save(true, monitor); monitor.worked(1); return server; } /** * Fills in the environment given with the values in the environment * description. * * @see ElasticBeanstalkPlugin#importEnvironment(EnvironmentDescription, IProgressMonitor) */ private static void fillInEnvironmentValues(EnvironmentDescription elasticBeanstalkEnv, Environment env, IProgressMonitor monitor) { ElasticBeanstalkClientExtensions clientExt = new ElasticBeanstalkClientExtensions(env); monitor.subTask("Getting application info"); ApplicationDescription applicationDesc = clientExt.getApplicationDescription(elasticBeanstalkEnv .getApplicationName()); if (applicationDesc != null) { env.setApplicationDescription(applicationDesc.getDescription()); } monitor.worked(1); monitor.subTask("Getting environment configuration"); List<ConfigurationSettingsDescription> currentSettings = env.getCurrentSettings(); for ( ConfigurationSettingsDescription settingDescription : currentSettings ) { for ( ConfigurationOptionSetting setting : settingDescription.getOptionSettings() ) { if ( setting.getNamespace().equals("aws:autoscaling:launchconfiguration") && setting.getOptionName().equals("EC2KeyName") ) { env.setKeyPairName(setting.getValue()); } } } monitor.worked(1); env.setCname(elasticBeanstalkEnv.getCNAME()); env.setEnvironmentDescription(elasticBeanstalkEnv.getDescription()); } /** * Listens for the creation of new elastic beanstalk servers and syncs all * environments' status. */ private class NewServerListener implements IServerLifecycleListener { @Override public void serverAdded(IServer server) { if ( SERVER_TYPE_IDS.contains(server.getServerType().getId()) ) { ElasticBeanstalkPlugin.getDefault().syncEnvironments(); } } @Override public void serverChanged(IServer server) { } @Override public void serverRemoved(IServer server) { } } }
7,350
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ElasticBeanstalkLaunchableAdapter.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import java.util.HashMap; import java.util.Map; import org.eclipse.jst.server.core.IWebModule; import org.eclipse.jst.server.core.Servlet; import org.eclipse.wst.server.core.IModuleArtifact; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.model.LaunchableAdapterDelegate; import org.eclipse.wst.server.core.model.ServerDelegate; import org.eclipse.wst.server.core.util.WebResource; public class ElasticBeanstalkLaunchableAdapter extends LaunchableAdapterDelegate { private static final Map<String, ElasticBeanstalkHttpLaunchable> launchables = new HashMap<>(); /** * Returns the launchable currently associated with the given server. */ public static ElasticBeanstalkHttpLaunchable getLaunchable(IServer server) { return launchables.get(server.getId()); } @Override public Object getLaunchable(IServer server, IModuleArtifact moduleArtifact) { Object serverDelegate = server.loadAdapter(ServerDelegate.class, null); if (serverDelegate instanceof Environment == false) { return null; } if (!(moduleArtifact instanceof Servlet) && !(moduleArtifact instanceof WebResource)) return null; if (moduleArtifact.getModule().loadAdapter(IWebModule.class, null) == null) return null; ElasticBeanstalkHttpLaunchable launchable = new ElasticBeanstalkHttpLaunchable(server, moduleArtifact); launchables.put(server.getId(), launchable); return launchable; } }
7,351
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/OpenElasticBeanstalkConsoleAction.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import com.amazonaws.eclipse.core.BrowserUtils; public class OpenElasticBeanstalkConsoleAction implements IObjectActionDelegate { private static final String ELASTIC_BEANSTALK_CONSOLE_URL = "https://console.aws.amazon.com/elasticbeanstalk"; @Override public void run(IAction action) { BrowserUtils.openExternalBrowser(ELASTIC_BEANSTALK_CONSOLE_URL); } @Override public void selectionChanged(IAction action, ISelection selection) {} @Override public void setActivePart(IAction action, IWorkbenchPart targetPart) {} }
7,352
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ElasticBeanstalkOverviewSection.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import com.amazonaws.eclipse.core.AwsUrls; import com.amazonaws.eclipse.core.ui.overview.OverviewSection; import com.amazonaws.eclipse.elasticbeanstalk.server.ui.ImportEnvironmentsWizard; import com.amazonaws.eclipse.elasticbeanstalk.webproject.NewAwsJavaWebProjectWizard; /** * AWS Elastic Beanstalk specific section on the AWS Toolkit for Eclipse overview page. */ public class ElasticBeanstalkOverviewSection extends OverviewSection implements OverviewSection.V2 { private static final String ELASTIC_BEANSTALK_GETTING_STARTED_GUIDE_URL = "http://aws.amazon.com/articles/4412341514662386" + "?" + AwsUrls.TRACKING_PARAMS; private static final String ELASTIC_BEANSTALK_ECLIPSE_SCREENCAST_URL = "http://d1un85p0f2qstc.cloudfront.net/eclipse/elasticbeanstalk/index.html" + "?" + AwsUrls.TRACKING_PARAMS; @Override public void createControls(Composite parent) { Composite tasksSection = toolkit.newSubSection(parent, "Tasks"); toolkit.newListItem(tasksSection, "Create a New AWS Java Web Project", null, openNewAwsJavaWebProjectAction); toolkit.newListItem(tasksSection, "Import Existing Environments", null, openImportEnvironmentsWizard); Composite resourcesSection = toolkit.newSubSection(parent, "Additional Resources"); toolkit.newListItem(resourcesSection, "Getting Started with AWS Elastic Beanstalk Deployment in Eclipse", ELASTIC_BEANSTALK_GETTING_STARTED_GUIDE_URL); this.toolkit.newListItem(resourcesSection, "Video: Overview of AWS Elastic Beanstalk Deployment in Eclipse", ELASTIC_BEANSTALK_ECLIPSE_SCREENCAST_URL); } /** Action to open the New AWS Java Project wizard in a dialog */ private static final IAction openNewAwsJavaWebProjectAction = new Action() { @Override public void run() { NewAwsJavaWebProjectWizard newWizard = new NewAwsJavaWebProjectWizard(); newWizard.init(PlatformUI.getWorkbench(), null); WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), newWizard); dialog.open(); } }; private static final IAction openImportEnvironmentsWizard = new Action() { @Override public void run() { ImportEnvironmentsWizard newWizard = new ImportEnvironmentsWizard(); WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), newWizard); dialog.open(); } }; }
7,353
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ui/menu/DeployToElasticBeanstalkHandler.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.ui.menu; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.wst.server.ui.actions.RunOnServerAction; public class DeployToElasticBeanstalkHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection(); if ( selection != null & selection instanceof IStructuredSelection ) { IStructuredSelection structurredSelection = (IStructuredSelection)selection; new RunOnServerAction(structurredSelection.getFirstElement()).run(); } return null; } }
7,354
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ui/menu/NewAwsJavaWebProjectHandler.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.elasticbeanstalk.ui.menu; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import com.amazonaws.eclipse.elasticbeanstalk.webproject.NewAwsJavaWebProjectWizard; public class NewAwsJavaWebProjectHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { NewAwsJavaWebProjectWizard newWizard = new NewAwsJavaWebProjectWizard(); newWizard.init(PlatformUI.getWorkbench(), null); WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard); return dialog.open(); } }
7,355
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/ui/menu/NewEnvironmentHandler.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.elasticbeanstalk.ui.menu; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import org.eclipse.wst.server.ui.internal.wizard.NewServerWizard; public class NewEnvironmentHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { NewServerWizard wizard = new NewServerWizard(); wizard.init(PlatformUI.getWorkbench(), new StructuredSelection()); WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), wizard); return dialog.open(); } }
7,356
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/util/PollForEvent.java
/* * Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.util; import java.util.concurrent.TimeUnit; /** * Class to poll until a given {@link Event} has occurred at a specified interval and up to a max * number of iterations */ public class PollForEvent { /** * Interface to represent a certain event and whether it has occurred or not. */ public interface Event { /** * @return True if event has occurred, false otherwise */ public boolean hasEventOccurred(); } /** * Represents an interval of time with units specified */ public static class Interval { private final long millis; public Interval(long value, TimeUnit unit) { millis = unit.toMillis(value); } private long getMillis() { return millis; } } private final Interval interval; private final long maxNumberOfIntervalsToPollFor; /** * @param interval * {@link Interval} of time to wait between checking the event status * @param maxNumberOfIntervalsToPollFor * Max intervals to poll for before giving up */ public PollForEvent(Interval interval, int maxNumberOfIntervalsToPollFor) { this.interval = interval; this.maxNumberOfIntervalsToPollFor = maxNumberOfIntervalsToPollFor; } public void poll(Event event) { int currentPollInterval = 0; while (!event.hasEventOccurred() && !hasReachedMaxPollInterval(currentPollInterval)) { try { Thread.sleep(interval.getMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } currentPollInterval++; } } public boolean hasReachedMaxPollInterval(int currentPollInterval) { return currentPollInterval >= maxNumberOfIntervalsToPollFor; } }
7,357
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/util/BeanstalkConstants.java
/* * Copyright 2015 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.util; public class BeanstalkConstants { public static final String DEFAULT_INSTANCE_ROLE_NAME = "aws-elasticbeanstalk-ec2-role"; public static final String DEFAULT_SERVICE_ROLE_NAME = "aws-elasticbeanstalk-service-role"; public static final String ELB_SCHEME_EXTERNAL = "external"; public static final String ELB_SCHEME_INTERNAL = "internal"; }
7,358
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/util/ElasticBeanstalkClientExtensions.java
/* * Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.util; import java.util.List; import com.amazonaws.eclipse.elasticbeanstalk.Environment; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.ApplicationDescription; import com.amazonaws.services.elasticbeanstalk.model.ApplicationVersionDescription; import com.amazonaws.services.elasticbeanstalk.model.DescribeApplicationVersionsRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeApplicationsRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentsRequest; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentStatus; /** * Wrapper around Beanstalk client to add several convenience extension methods */ public class ElasticBeanstalkClientExtensions { private final AWSElasticBeanstalk client; public ElasticBeanstalkClientExtensions(Environment environment) { this(environment.getClient()); } public ElasticBeanstalkClientExtensions(AWSElasticBeanstalk client) { this.client = client; } /** * @param environmentName * Name of environment to get CNAME for * @return Environment's CNAME */ public String getEnvironmentCname(String environmentName) { EnvironmentDescription environmentDesc = getEnvironmentDescription(environmentName); if (environmentDesc == null) { return null; } else { return environmentDesc.getCNAME(); } } /** * @param environmentName * @return {@link EnvironmentDescription} for a given environment */ public EnvironmentDescription getEnvironmentDescription(String environmentName) { List<EnvironmentDescription> environments = client.describeEnvironments( new DescribeEnvironmentsRequest().withEnvironmentNames(environmentName)).getEnvironments(); return getFirstOrNull(environments); } /** * @param applicationName * @param environmentName * @return {@link EnvironmentDescription} for a given application/environment */ public EnvironmentDescription getEnvironmentDescription(String applicationName, String environmentName) { List<EnvironmentDescription> environments = client.describeEnvironments( new DescribeEnvironmentsRequest().withApplicationName(applicationName).withEnvironmentNames( environmentName)).getEnvironments(); return getFirstOrNull(environments); } /** * @param applicationName * @return {@link ApplicationDescription} of the specified application */ public ApplicationDescription getApplicationDescription(String applicationName) { List<ApplicationDescription> applications = client.describeApplications( new DescribeApplicationsRequest().withApplicationNames(applicationName)).getApplications(); return getFirstOrNull(applications); } /** * @param applicationName * @return Latest {@link ApplicationVersionDescription} for the specified application */ public ApplicationVersionDescription getLatestApplicationVersionDescription(String applicationName) { List<ApplicationVersionDescription> applicationVersions = client.describeApplicationVersions( new DescribeApplicationVersionsRequest().withApplicationName(applicationName)).getApplicationVersions(); return getFirstOrNull(applicationVersions); } /** * @param applicationName * @return True if application exists in Beanstalk */ public boolean doesApplicationExist(String applicationName) { return getApplicationDescription(applicationName) != null; } /** * @param environmentName * @return True if environment exists in any application. False otherwise */ public boolean doesEnvironmentExist(String environmentName) { EnvironmentDescription environment = getEnvironmentDescription(environmentName); if (environment == null) { return false; } return !isStatusTerminatedOrTerminating(environment.getStatus()); } /** * @param applicationName * @param environmentName * @return True if environment exists in the specified application. False otherwise. */ public boolean doesEnvironmentExist(String applicationName, String environmentName) { EnvironmentDescription environment = getEnvironmentDescription(applicationName, environmentName); if (environment == null) { return false; } return !isStatusTerminatedOrTerminating(environment.getStatus()); } /** * @return The Beanstalk client this class is wrapping */ public AWSElasticBeanstalk getClient() { return client; } /** * @param list * @return The first element of the list or null if the list provided is null or empty */ private static <T> T getFirstOrNull(List<T> list) { if (list.isEmpty()) { return null; } else { return list.get(0); } } private static boolean isStatusTerminatedOrTerminating(String status) { if (status.equals(EnvironmentStatus.Terminated.toString()) || status.equals(EnvironmentStatus.Terminating.toString())) { return true; } return false; } }
7,359
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/util/OnUiThreadProxyFactory.java
/* * Copyright 2015 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.util; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; import java.util.concurrent.atomic.AtomicReference; import org.eclipse.swt.widgets.Display; /** * Proxy Factory to create a dynamic proxy that will intercept all method calls and run them on the * UI thread of the default {@link Display} */ public final class OnUiThreadProxyFactory { /** * Get dynamic proxy that will run all method calls on the UI thread * * @param interfaceClass * Interface to proxy * @param interfaceImpl * Implementation to delegate calls to after wrapping them in a runnable to invoke on * the UI thread * @return Proxy class */ public static <T> T getProxy(Class<T> interfaceClass, T interfaceImpl) { Object proxy = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] { interfaceClass }, new OnUiThreadProxyFactory.OnUiThreadProxyHandler<>(interfaceImpl)); return interfaceClass.cast(proxy); } /** * Smiple handler to wrap calls in a runnable and submit them to be run on the UI thread of the * default display * * @param <T> * Type of interface being proxied */ private static final class OnUiThreadProxyHandler<T> implements InvocationHandler { private final T interfaceImpl; public OnUiThreadProxyHandler(T impl) { this.interfaceImpl = impl; } @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { final AtomicReference<Object> toReturnRef = new AtomicReference<>(); final AtomicReference<Throwable> throwRef = new AtomicReference<>(); Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { toReturnRef.set(method.invoke(interfaceImpl, args)); } catch (InvocationTargetException e) { throwRef.set(e.getTargetException()); } catch (UndeclaredThrowableException e) { throwRef.set(e.getUndeclaredThrowable()); } catch (Exception e) { throwRef.set(e); } } }); // Throw the exception if any if (throwRef.get() != null) { throw throwRef.get(); } return toReturnRef.get(); } } }
7,360
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/solutionstacks/Tomcat8SolutionStacks.java
/* * Copyright 2011-2014 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.elasticbeanstalk.solutionstacks; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.SolutionStackDescription; class Tomcat8SolutionStacks { /** * The String constant for Tomcat 8. This is used as the fall-back value for * Tomcat 8, if we fail to retrieve the latest solution-stack name from the * DescribeSolutionStacks API. */ private static final String TOMCAT_8_64BIT_AMAZON_LINUX_v2_5_2 = "64bit Amazon Linux 2016.09 v2.5.2 running Tomcat 8 Java 8"; private static final String SIX_FOUR_BIT_PREFIX = "64bit Amazon Linux "; private static final String TOMCAT_8_Java_8_SUFFIX = " running Tomcat 8 Java 8"; /** * Look up the latest solution stack name for Tomcat 7, by using the * DescribeSolutionStacks API. * * @return The solution stack name returned by the * ListAvailableSolutionStacks API, that has the latest internal * version number. */ public static String lookupLatestSolutionStackName() { AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory() .getElasticBeanstalkClient(); return lookupLatestSolutionStackName(client); } /** * Look up the latest solution stack name for Tomcat 8, by using the * DescribeSolutionStacks API. */ static String lookupLatestSolutionStackName(AWSElasticBeanstalk client) { try { List<String> tomcat8Java864bitStacks = new ArrayList<>(); for (SolutionStackDescription ss : client.listAvailableSolutionStacks().getSolutionStackDetails()) { String ssName = ss.getSolutionStackName(); if (ssName != null && ssName.startsWith(SIX_FOUR_BIT_PREFIX) && ssName.endsWith(TOMCAT_8_Java_8_SUFFIX)) { tomcat8Java864bitStacks.add(ssName); } } if ( !tomcat8Java864bitStacks.isEmpty() ) { Collections.sort(tomcat8Java864bitStacks); // The last element in lexicographically ascending order String latest = tomcat8Java864bitStacks.get(tomcat8Java864bitStacks.size() - 1); AwsToolkitCore.getDefault().logInfo( "Found the latest solution stack name: " + latest); return latest; } AwsToolkitCore.getDefault().logInfo( "Unabled to look up the latest solution stack name for Tomcat 8."); } catch (Exception e) { AwsToolkitCore.getDefault().logInfo( "Unabled to look up the latest solution stack name for Tomcat 8." + e.getMessage()); } // returns the hard-coded string constant as fall-back return TOMCAT_8_64BIT_AMAZON_LINUX_v2_5_2; } }
7,361
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/solutionstacks/TomcatVersion.java
/* * Copyright 2011-2014 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.elasticbeanstalk.solutionstacks; /** * Enumeration of Tomcat versions supported by the AWS Elastic Beanstalk * plug-in. */ enum TomcatVersion { TOMCAT_6, TOMCAT_7, TOMCAT_8 }
7,362
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/solutionstacks/Tomcat7SolutionStacks.java
/* * Copyright 2011-2014 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.elasticbeanstalk.solutionstacks; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.SolutionStackDescription; class Tomcat7SolutionStacks { /** * The String constant for Tomcat 7. This is used as the fall-back value for * Tomcat 7, if we fail to retrieve the latest solution-stack name from the * DescribeSolutionStacks API. */ private static final String TOMCAT_7_64BIT_AMAZON_LINUX_v2_5_2 = "64bit Amazon Linux 2016.09 v2.5.2 running Tomcat 7 Java 7"; private static final String SIX_FOUR_BIT_PREFIX = "64bit Amazon Linux "; private static final String TOMCAT_7_Java_7_SUFFIX = " running Tomcat 7 Java 7"; /** * Look up the latest solution stack name for Tomcat 7, by using the * DescribeSolutionStacks API. * * @return The solution stack name returned by the * ListAvailableSolutionStacks API, that has the latest internal * version number. */ public static String lookupLatestSolutionStackName() { AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory() .getElasticBeanstalkClient(); return lookupLatestSolutionStackName(client); } /** * Look up the latest solution stack name for Tomcat 7, by using the * DescribeSolutionStacks API. */ static String lookupLatestSolutionStackName(AWSElasticBeanstalk client) { try { List<String> tomcat7Java764bitStacks = new ArrayList<>(); for (SolutionStackDescription ss : client.listAvailableSolutionStacks().getSolutionStackDetails()) { String ssName = ss.getSolutionStackName(); if (ssName != null && ssName.startsWith(SIX_FOUR_BIT_PREFIX) && ssName.endsWith(TOMCAT_7_Java_7_SUFFIX)) { tomcat7Java764bitStacks.add(ssName); } } if ( !tomcat7Java764bitStacks.isEmpty() ) { Collections.sort(tomcat7Java764bitStacks); // The last element in lexicographically ascending order String latest = tomcat7Java764bitStacks.get(tomcat7Java764bitStacks.size() - 1); AwsToolkitCore.getDefault().logInfo( "Found the latest solution stack name: " + latest); return latest; } AwsToolkitCore.getDefault().logInfo( "Unabled to look up the latest solution stack name for Tomcat 7."); } catch (Exception e) { AwsToolkitCore.getDefault().logInfo( "Unabled to look up the latest solution stack name for Tomcat 7." + e.getMessage()); } // returns the hard-coded string constant as fall-back return TOMCAT_7_64BIT_AMAZON_LINUX_v2_5_2; } }
7,363
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/solutionstacks/SolutionStacks.java
/* * Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.solutionstacks; import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin; public class SolutionStacks { /** * The String constant for Tomcat 6. */ private static final String TOMCAT_6_64BIT_AMAZON_LINUX = "64bit Amazon Linux running Tomcat 6"; public static String lookupSolutionStackByServerTypeId(String serverTypeId) { if (serverTypeId.equalsIgnoreCase(ElasticBeanstalkPlugin.TOMCAT_6_SERVER_TYPE_ID)) { return getSolutionStackNameByTomcatVersion(TomcatVersion.TOMCAT_6); } else if (serverTypeId.equalsIgnoreCase(ElasticBeanstalkPlugin.TOMCAT_7_SERVER_TYPE_ID)) { return getSolutionStackNameByTomcatVersion(TomcatVersion.TOMCAT_7); } else if (serverTypeId.equalsIgnoreCase(ElasticBeanstalkPlugin.TOMCAT_8_SERVER_TYPE_ID)) { return getSolutionStackNameByTomcatVersion(TomcatVersion.TOMCAT_8); } throw new RuntimeException("Unknown server type: " + serverTypeId); } public static String lookupServerTypeIdBySolutionStack(String solutionStack) { if (solutionStack.contains(" Tomcat 6")) { return ElasticBeanstalkPlugin.TOMCAT_6_SERVER_TYPE_ID; } else if (solutionStack.contains(" Tomcat 7")) { return ElasticBeanstalkPlugin.TOMCAT_7_SERVER_TYPE_ID; } else if (solutionStack.contains(" Tomcat 8")) { return ElasticBeanstalkPlugin.TOMCAT_8_SERVER_TYPE_ID; } throw new RuntimeException("Unsupported solution stack: " + solutionStack); } public static String getDefaultSolutionStackName() { return getSolutionStackNameByTomcatVersion(TomcatVersion.TOMCAT_8); } /** * Returns the appropriate solution stack name String to use to create an * Elastic Beanstalk environment running the specified Tomcat version. * * @param version * Enumeration of the Tomcat software version. */ private static String getSolutionStackNameByTomcatVersion(TomcatVersion version) { switch (version) { case TOMCAT_6: return TOMCAT_6_64BIT_AMAZON_LINUX; case TOMCAT_7: return Tomcat7SolutionStacks.lookupLatestSolutionStackName(); case TOMCAT_8: return Tomcat8SolutionStacks.lookupLatestSolutionStackName(); default: throw new RuntimeException("Unknown Tomcat version: " + version); } } }
7,364
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/deploy/WTPWarUtils.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.deploy; import java.io.File; import java.io.IOException; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jst.j2ee.datamodel.properties.IJ2EEComponentExportDataModelProperties; import org.eclipse.jst.j2ee.internal.web.archive.operations.WebComponentExportDataModelProvider; import org.eclipse.wst.common.frameworks.datamodel.DataModelFactory; import org.eclipse.wst.common.frameworks.datamodel.IDataModel; import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation; /** * Utilities for exporting Web Tools Platform Java web application projects to * WAR files. */ public class WTPWarUtils { public static IPath exportProjectToWar(IProject project, IPath directory) { File tempFile; try { tempFile = File.createTempFile("aws-eclipse-", ".war", directory.toFile()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Unable to create web application archive: " + e.getMessage(), e); } return exportProjectToWar(project, directory, tempFile.getName()); } public static IPath exportProjectToWar(IProject project, IPath directory, String fileName) { IDataModel dataModel = DataModelFactory.createDataModel(new WebComponentExportDataModelProvider()); if (directory.toFile().exists() == false) { if (directory.toFile().mkdirs() == false) { throw new RuntimeException("Unable to create temp directory for web application archive."); } } String filename = new File(directory.toFile(), fileName).getAbsolutePath(); dataModel.setProperty(IJ2EEComponentExportDataModelProperties.ARCHIVE_DESTINATION, filename); dataModel.setProperty(IJ2EEComponentExportDataModelProperties.PROJECT_NAME, project.getName()); try { IDataModelOperation operation = dataModel.getDefaultOperation(); operation.execute(new NullProgressMonitor(), null); } catch (ExecutionException e) { // TODO: better error handling e.printStackTrace(); throw new RuntimeException("Unable to create web application archive: " + e.getMessage(), e); } return new Path(filename); } }
7,365
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/deploy/DeployWizardDataModel.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.deploy; import static com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin.trace; import java.util.HashSet; import java.util.Set; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.ec2.ui.keypair.KeyPairComposite; import com.amazonaws.services.ec2.model.KeyPairInfo; public class DeployWizardDataModel { // Bean property name constants public static final String EXISTING_APPLICATION_NAME = "existingApplicationName"; public static final String CREATING_NEW_APPLICATION = "creatingNewApplication"; public static final String NEW_APPLICATION_NAME = "newApplicationName"; public static final String NEW_APPLICATION_DESCRIPTION = "newApplicationDescription"; public static final String VERSION_RELEASE_LABEL = "versionReleaseLabel"; public static final String VERSION_DESCRIPTION = "versionDescription"; public static final String EXISTING_S3_BUCKET_NAME = "existingS3BucketName"; public static final String CREATING_NEW_S3_BUCKET = "creatingNewS3Bucket"; public static final String NEW_S3_BUCKET_NAME = "newS3BucketName"; public static final String NEW_ENVIRONMENT_NAME = "newEnvironmentName"; public static final String NEW_ENVIRONMENT_DESCRIPTION = "newEnvironmentDescription"; public static final String ENVIRONMENT_TYPE = "environmentType"; public static final String USING_KEY_PAIR = "usingKeyPair"; public static final String KEY_PAIR = "keyPair"; public static final String USING_CNAME = "usingCname"; public static final String CNAME = "cname"; public static final String INCREMENTAL_DEPLOYMENT = "incrementalDeployment"; public static final String SNS_ENDPOINT = "snsEndpoint"; public static final String SSL_CERTIFICATE_ID = "sslCertificateId"; public static final String HEALTH_CHECK_URL = "healthCheckUrl"; public static final String USE_NON_DEFAULT_VPC = "useNonDefaultVpc"; public static final String VPC_ID = "vpcId"; public static final String ELB_SCHEME = "elbScheme"; public static final String SECURITY_GROUP = "securityGroup"; public static final String ASSOCIATE_PUBLIC_IP_ADDRESS = "associatePublicIpAddress"; public static final String INSTANCE_ROLE_NAME = "instanceRoleName"; public static final String SERVICE_ROLE_NAME = "serviceRoleName"; public static final String REGION_ENDPOINT = "regionEndpoint"; public static final String WORKER_QUEUE_URL = "workerQueueUrl"; private Region region; private String existingApplicationName; private boolean isCreatingNewApplication; private String newApplicationName; private String newApplicationDescription; private String newEnvironmentName; private String newEnvironmentDescription; private String environmentType; private boolean usingCname = false; private String cname; private boolean usingKeyPair = false; private KeyPairInfo keyPair; private boolean incrementalDeployment = false; private String snsEndpoint; private String healthCheckUrl; private String sslCertificateId; private boolean useNonDefaultVpc; private String vpcId; private final Set<String> ec2Subnets = new HashSet<>(); private final Set<String> elbSubnets = new HashSet<>(); private String elbScheme; private String securityGroup; private boolean associatePublicIpAddress; private String instanceRoleName; private String serviceRoleName; private boolean skipIamRoleAndInstanceProfileCreation; private String workerQueueUrl; // Share reference to make is easy to update the composite when region // changed. private KeyPairComposite keyPairComposite; public boolean isIncrementalDeployment() { return incrementalDeployment; } public void setIncrementalDeployment(boolean b) { this.incrementalDeployment = b; } public boolean isUsingKeyPair() { return usingKeyPair; } public void setUsingKeyPair(boolean usingKeyPair) { trace("Setting using key pair = " + usingKeyPair); this.usingKeyPair = usingKeyPair; } public boolean isUsingCname() { return usingCname; } public void setUsingCname(boolean usingCname) { trace("Setting using cname = " + usingCname); this.usingCname = usingCname; } public String getCname() { return cname; } public void setCname(String cname) { trace("Setting cname = " + cname); this.cname = cname; } public KeyPairInfo getKeyPair() { return keyPair; } public void setKeyPair(KeyPairInfo keyPair) { trace("Setting key pair = " + keyPair); this.keyPair = keyPair; } public String getApplicationName() { if (isCreatingNewApplication) { return newApplicationName; } return existingApplicationName; } public String getExistingApplicationName() { return existingApplicationName; } public void setExistingApplicationName(String existingApplicationName) { trace("Setting existing application name = " + existingApplicationName); this.existingApplicationName = existingApplicationName; } public boolean isCreatingNewApplication() { return isCreatingNewApplication; } public void setCreatingNewApplication(boolean isCreatingNewApplication) { trace("Setting creating new application = " + isCreatingNewApplication); this.isCreatingNewApplication = isCreatingNewApplication; } public String getNewApplicationName() { return newApplicationName; } public void setNewApplicationName(String newApplicationName) { trace("Setting new application name = " + newApplicationName); this.newApplicationName = newApplicationName; } public String getNewApplicationDescription() { return newApplicationDescription; } public void setNewApplicationDescription(String newApplicationDescription) { trace("Setting new application description = " + newApplicationDescription); this.newApplicationDescription = newApplicationDescription; } // Environment Options public String getEnvironmentName() { return newEnvironmentName; } public String getNewEnvironmentName() { return newEnvironmentName; } public void setNewEnvironmentName(String newEnvironmentName) { trace("Setting new environment name = " + newEnvironmentName); this.newEnvironmentName = newEnvironmentName; } public String getNewEnvironmentDescription() { return newEnvironmentDescription; } public void setNewEnvironmentDescription(String newEnvironmentDescription) { trace("Setting new environment description = " + newEnvironmentDescription); this.newEnvironmentDescription = newEnvironmentDescription; } public String getEnvironmentType() { return environmentType; } public void setEnvironmentType(String environmentType) { this.environmentType = environmentType; } public String getRegionEndpoint() { return getRegion().getServiceEndpoints().get(ServiceAbbreviations.BEANSTALK); } public String getSnsEndpoint() { return snsEndpoint; } public String getEc2Endpoint() { return getRegion().getServiceEndpoints().get(ServiceAbbreviations.EC2); } public void setSnsEndpoint(String snsEndpoint) { trace("Setting sns endpoint = " + snsEndpoint); this.snsEndpoint = snsEndpoint; } public void setRegion(Region region) { this.region = region; } public Region getRegion() { return this.region; } public String getHealthCheckUrl() { return healthCheckUrl; } public void setHealthCheckUrl(String healthCheckUrl) { trace("Setting healthcheck url = " + healthCheckUrl); this.healthCheckUrl = healthCheckUrl; } public String getSslCertificateId() { return sslCertificateId; } public void setSslCertificateId(String sslCertificateId) { trace("Setting ssl certificate id = " + sslCertificateId); this.sslCertificateId = sslCertificateId; } public void setKeyPairComposite(KeyPairComposite keyPairComposite) { this.keyPairComposite = keyPairComposite; } public KeyPairComposite getKeyPairComposite() { return keyPairComposite; } public String getVpcId() { return vpcId; } /** * Sets the optional VPC id to be used when creating environment. * * @param vpcId the VPC to be used when creating environment. */ public void setVpcId(String vpcId) { this.vpcId = vpcId; } public String getSecurityGroup() { return securityGroup; } public void setSecurityGroup(String securityGroup) { this.securityGroup = securityGroup; } public boolean isUseNonDefaultVpc() { return useNonDefaultVpc; } public void setUseNonDefaultVpc(boolean useNonDefaultVpc) { this.useNonDefaultVpc = useNonDefaultVpc; } public Set<String> getEc2Subnets() { return ec2Subnets; } public Set<String> getElbSubnets() { return elbSubnets; } public String getElbScheme() { return elbScheme; } public void setElbScheme(String elbScheme) { this.elbScheme = elbScheme; } public boolean isAssociatePublicIpAddress() { return associatePublicIpAddress; } public void setAssociatePublicIpAddress(boolean associatePublicIpAddress) { this.associatePublicIpAddress = associatePublicIpAddress; } /** * Sets the optional IAM role to use when launching this environment. Using a role will cause it * to be available on the EC2 instances running as part of the Beanstalk environment, and allow * applications to securely access credentials from that role. * * @param role * The role with which to launch EC2 instances in the Beanstalk environment. */ public void setInstanceRoleName(String roleName) { this.instanceRoleName = roleName; } /** * Returns the optional IAM role to use when launching this environment. Using a role will cause * the role's security credentials to be securely distributed to the EC2 instances running as * part of the Beanstalk environment. * * @return The optional role name with which to launch EC2 instances in the Beanstalk * environment. */ public String getInstanceRoleName() { return instanceRoleName; } /** * Returns the name of the optional IAM role that the service (ElasticBeanstalk) is allowed to * impersonate. Currently this is only used for Enhanced Health reporting/monitoring * * @return The name of the role that ElasticBeanstalk can assume */ public String getServiceRoleName() { return serviceRoleName; } /** * Sets the name of the optional IAM role that the service (ElasticBeanstalk) is allowed to * impersonate. Currently this is only used for Enhanced Health reporting/monitoring * * @param serviceRoleName * The name of the role that ElasticBeanstalk can assume */ public void setServiceRoleName(String serviceRoleName) { this.serviceRoleName = serviceRoleName; } /** * Returns true if the name of the IAM role/Instance Profile is directly provided via user input * and that the plugin should not attempt to re-create them. */ public boolean isSkipIamRoleAndInstanceProfileCreation() { return skipIamRoleAndInstanceProfileCreation; } public void setSkipIamRoleAndInstanceProfileCreation(boolean skipIamRoleAndInstanceProfileCreation) { this.skipIamRoleAndInstanceProfileCreation = skipIamRoleAndInstanceProfileCreation; } public String getWorkerQueueUrl() { return workerQueueUrl; } public void setWorkerQueueUrl(String value) { workerQueueUrl = value; } }
7,366
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/deploy/NotEmptyValidator.java
/* * Copyright 2010-2012 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.deploy; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.swt.widgets.Button; public class NotEmptyValidator implements IValidator { protected final ControlDecoration controlDecoration; protected Button button; public NotEmptyValidator(ControlDecoration controlDecoration, Button button) { this.controlDecoration = controlDecoration; this.button = button; } /* (non-Javadoc) * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object) */ @Override public IStatus validate(Object value) { if (value instanceof String == false) { throw new RuntimeException("Only string validation is supported."); } // If a button has been specified and it isn't selected, then // we don't need to do any validation and can bail out. if (button != null && button.getSelection() == false) { controlDecoration.hide(); return ValidationStatus.ok(); } String s = (String)value; if (s != null && s.trim().length() > 0) { controlDecoration.hide(); return ValidationStatus.ok(); } else { controlDecoration.show(); return ValidationStatus.info(controlDecoration.getDescriptionText()); } } }
7,367
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/resources/BeanstalkResourceProvider.java
/* * Copyright 2015 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.resources; import java.io.IOException; import java.io.InputStream; import com.amazonaws.util.IOUtils; /** * Provides access to resources on the class path. Only handles text files with absolute resource * paths currently. */ public class BeanstalkResourceProvider { private static final String RESOURCES_PATH = "/com/amazonaws/eclipse/elasticbeanstalk/resources"; private static BeanstalkResource SERVICE_ROLE_PERMISSIONS_POLICY = new BeanstalkResource(RESOURCES_PATH + "/service-role-permissions-policy.json"); private static BeanstalkResource SERVICE_ROLE_TRUST_POLICY = new BeanstalkResource(RESOURCES_PATH + "/service-role-trust-policy.json"); private static BeanstalkResource INSTANCE_PROFILE_PERMISSIONS_POLICY = new BeanstalkResource(RESOURCES_PATH + "/instance-profile-permissions-policy.json"); private static BeanstalkResource INSTANCE_PROFILE_TRUST_POLICY = new BeanstalkResource(RESOURCES_PATH + "/instance-profile-trust-policy.json"); private static BeanstalkResource MINIMUM_IAM_PERMISSIONS_POLICY = new BeanstalkResource(RESOURCES_PATH + "/minimum-iam-permissions-policy.json"); public BeanstalkResource getServiceRolePermissionsPolicy() { return SERVICE_ROLE_PERMISSIONS_POLICY; } public BeanstalkResource getServiceRoleTrustPolicy() { return SERVICE_ROLE_TRUST_POLICY; } public BeanstalkResource getInstanceProfilePermissionsPolicy() { return INSTANCE_PROFILE_PERMISSIONS_POLICY; } public BeanstalkResource getInstanceProfileTrustPolicy() { return INSTANCE_PROFILE_TRUST_POLICY; } public BeanstalkResource getMinimumIamPermissionsPolicy() { return MINIMUM_IAM_PERMISSIONS_POLICY; } /** * Represents a resource on the classpath and provides utility methods for accessing it's data */ public static class BeanstalkResource { private final String resourcePath; public BeanstalkResource(String resourcePath) { this.resourcePath = resourcePath; } public String asString() { return getResourceAsString(resourcePath); } public InputStream asStream() { return BeanstalkResourceProvider.class.getResourceAsStream(resourcePath); } private String getResourceAsString(String resourcePath) { return BeanstalkResourceProvider.toString(asStream()); } } private static String toString(InputStream is) { if (is != null) { try { String content = IOUtils.toString(is); IOUtils.closeQuietly(is, null); return content; } catch (IOException e) { IOUtils.closeQuietly(is, null); throw new RuntimeException(e); } } return null; } }
7,368
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/explorer/ElasticBeanstalkActionProvider.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.elasticbeanstalk.explorer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.navigator.CommonActionProvider; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.eclipse.explorer.ContentProviderRegistry; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.ApplicationDescription; import com.amazonaws.services.elasticbeanstalk.model.DeleteApplicationRequest; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; import com.amazonaws.services.elasticbeanstalk.model.TerminateEnvironmentRequest; public class ElasticBeanstalkActionProvider extends CommonActionProvider { @Override public void fillContextMenu(IMenuManager menu) { boolean onlyEnvironmentsSelected = true; boolean onlyApplicationsSelected = true; StructuredSelection selection = (StructuredSelection)getActionSite().getStructuredViewer().getSelection(); @SuppressWarnings("rawtypes") Iterator iterator = selection.iterator(); List<EnvironmentDescription> environments = new ArrayList<>(); List<ApplicationDescription> applications = new ArrayList<>(); while ( iterator.hasNext() ) { Object obj = iterator.next(); if ( obj instanceof EnvironmentDescription ) { environments.add((EnvironmentDescription) obj); } else { onlyEnvironmentsSelected = false; } if ( obj instanceof ApplicationDescription ) { applications.add((ApplicationDescription) obj); } else { onlyApplicationsSelected = false; } } if ( onlyEnvironmentsSelected ) { if ( environments.size() == 1 ) { menu.add(new OpenEnvironmentEditorAction(environments.get(0), RegionUtils.getCurrentRegion())); menu.add(new Separator()); } menu.add(new TerminateEnvironmentsAction(environments)); } if ( onlyApplicationsSelected ) { menu.add(new DeleteApplicationAction(applications)); } } private static class TerminateEnvironmentsAction extends AwsAction { private final List<EnvironmentDescription> environments; public TerminateEnvironmentsAction(List<EnvironmentDescription> environments) { super(AwsToolkitMetricType.EXPLORER_BEANSTALK_TERMINATE_ENVIRONMENT); this.environments = environments; this.setText("Terminate Environment"); this.setToolTipText("Terminate the selected environments"); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE)); } @Override protected void doRun() { Dialog dialog = newConfirmationDialog("Terminate selected environments?", "Are you sure you want to terminate the selected AWS Elastic Beanstalk environments?"); if (dialog.open() != 0) { actionCanceled(); actionFinished(); return; } Job terminateEnvironmentsJob = new Job("Terminating Environments") { @Override protected IStatus run(IProgressMonitor monitor) { String endpoint = RegionUtils.getCurrentRegion().getServiceEndpoints().get(ServiceAbbreviations.BEANSTALK); AWSElasticBeanstalk beanstalk = AwsToolkitCore.getClientFactory().getElasticBeanstalkClientByEndpoint(endpoint); List<Exception> errors = new ArrayList<>(); for (EnvironmentDescription env : environments) { try { beanstalk.terminateEnvironment(new TerminateEnvironmentRequest().withEnvironmentId(env.getEnvironmentId())); } catch (Exception e) { errors.add(e); } } IStatus status = Status.OK_STATUS; if (errors.size() > 0) { status = new MultiStatus(ElasticBeanstalkPlugin.PLUGIN_ID, 0, "Unable to terminate environments", null); for (Exception error : errors) { ((MultiStatus)status).add(new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to terminate environment", error)); } actionFailed(); } else { actionSucceeded(); } actionFinished(); ContentProviderRegistry.refreshAllContentProviders(); return status; } }; terminateEnvironmentsJob.schedule(); } } private static class DeleteApplicationAction extends AwsAction { private final List<ApplicationDescription> applications; public DeleteApplicationAction(List<ApplicationDescription> applications) { super(AwsToolkitMetricType.EXPLORER_BEANSTALK_DELETE_APPLICATION); this.applications = applications; this.setText("Delete Application"); this.setToolTipText("Delete the selected application"); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE)); } @Override protected void doRun() { Dialog dialog = newConfirmationDialog("Delete selected application?", "Are you sure you want to delete the selected AWS Elastic Beanstalk applications?"); if (dialog.open() != 0) { actionCanceled(); actionFinished(); return; } Job deleteApplicationsJob = new Job("Delete Applications") { @Override protected IStatus run(IProgressMonitor monitor) { String endpoint = RegionUtils.getCurrentRegion().getServiceEndpoints().get(ServiceAbbreviations.BEANSTALK); AWSElasticBeanstalk beanstalk = AwsToolkitCore.getClientFactory().getElasticBeanstalkClientByEndpoint(endpoint); List<Exception> errors = new ArrayList<>(); for (ApplicationDescription app : applications) { try { beanstalk.deleteApplication(new DeleteApplicationRequest().withApplicationName(app.getApplicationName())); } catch (Exception e) { errors.add(e); } } IStatus status = Status.OK_STATUS; if (errors.size() > 0) { status = new MultiStatus(ElasticBeanstalkPlugin.PLUGIN_ID, 0, "Unable to delete applications", null); for (Exception error : errors) { ((MultiStatus)status).add(new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to delete application", error)); } actionFailed(); } else { actionSucceeded(); } actionFinished(); ContentProviderRegistry.refreshAllContentProviders(); return status; } }; deleteApplicationsJob.schedule(); } } private static Dialog newConfirmationDialog(String title, String message) { return new MessageDialog(Display.getDefault().getActiveShell(), title, null, message, MessageDialog.WARNING, new String[] { "OK", "Cancel" }, 0); } }
7,369
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/explorer/ElasticBeanstalkRootElement.java
package com.amazonaws.eclipse.elasticbeanstalk.explorer; /** * Root element for elastic beanstalk resources in the resource navigator. */ public class ElasticBeanstalkRootElement { public static final ElasticBeanstalkRootElement ROOT_ELEMENT = new ElasticBeanstalkRootElement(); private ElasticBeanstalkRootElement() { } }
7,370
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/explorer/ElasticBeanstalkContentProvider.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.elasticbeanstalk.explorer; import java.util.Iterator; import java.util.List; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.explorer.AWSResourcesRootElement; import com.amazonaws.eclipse.explorer.AbstractContentProvider; import com.amazonaws.eclipse.explorer.Loading; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.ApplicationDescription; import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentsRequest; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; public class ElasticBeanstalkContentProvider extends AbstractContentProvider implements ITreeContentProvider { private final IOpenListener listener = new IOpenListener() { @Override public void open(OpenEvent event) { StructuredSelection selection = (StructuredSelection) event.getSelection(); Iterator<?> i = selection.iterator(); while ( i.hasNext() ) { Object obj = i.next(); if ( obj instanceof EnvironmentDescription ) { EnvironmentDescription env = (EnvironmentDescription) obj; OpenEnvironmentEditorAction action = new OpenEnvironmentEditorAction(env, RegionUtils.getCurrentRegion()); action.run(); } } } }; @Override public void dispose() { viewer.removeOpenListener(listener); super.dispose(); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { super.inputChanged(viewer, oldInput, newInput); this.viewer.addOpenListener(listener); } @Override public String getServiceAbbreviation() { return ServiceAbbreviations.BEANSTALK; } @Override public Object[] loadChildren(final Object parentElement) { if ( parentElement instanceof AWSResourcesRootElement ) { return new Object[] { ElasticBeanstalkRootElement.ROOT_ELEMENT }; } if ( parentElement instanceof ElasticBeanstalkRootElement ) { new DataLoaderThread(parentElement) { @Override public Object[] loadData() { AWSElasticBeanstalk beanstalk = AwsToolkitCore.getClientFactory() .getElasticBeanstalkClient(); List<ApplicationDescription> applications = beanstalk.describeApplications().getApplications(); return applications.toArray(); } }.start(); } if ( parentElement instanceof ApplicationDescription ) { final ApplicationDescription app = (ApplicationDescription) parentElement; new DataLoaderThread(parentElement) { @Override public Object[] loadData() { AWSElasticBeanstalk beanstalk = AwsToolkitCore.getClientFactory() .getElasticBeanstalkClient(); List<EnvironmentDescription> environments = beanstalk.describeEnvironments( new DescribeEnvironmentsRequest().withApplicationName(app.getApplicationName())) .getEnvironments(); return environments.toArray(); } }.start(); } return Loading.LOADING; } @Override public boolean hasChildren(Object element) { return (element instanceof AWSResourcesRootElement || element instanceof ElasticBeanstalkRootElement || element instanceof ApplicationDescription); } }
7,371
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/explorer/OpenEnvironmentEditorAction.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.elasticbeanstalk.explorer; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.statushandlers.StatusManager; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.ui.internal.editor.ServerEditorInput; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; public class OpenEnvironmentEditorAction extends AwsAction { private final EnvironmentDescription env; private final Region region; public OpenEnvironmentEditorAction(EnvironmentDescription env, Region region) { super(AwsToolkitMetricType.EXPLORER_BEANSTALK_OPEN_ENVIRONMENT_EDITOR); this.env = env; this.region = region; this.setText("Open in WTP Server Editor"); } @Override protected void doRun() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IServer server = ElasticBeanstalkPlugin.getServer(env, region); if ( server == null ) { server = ElasticBeanstalkPlugin.importEnvironment(env, region, new NullProgressMonitor()); } activeWindow.getActivePage().openEditor(new ServerEditorInput(server.getId()), "org.eclipse.wst.server.ui.editor"); actionSucceeded(); } catch ( Exception e ) { actionFailed(); String errorMessage = "Unable to open the server editor: " + e.getMessage(); Status status = new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, errorMessage, e); StatusManager.getManager().handle(status, StatusManager.SHOW); } finally { actionFinished(); } } }); } }
7,372
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/explorer/ElasticBeanstalkLabelProvider.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.elasticbeanstalk.explorer; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin; import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider; import com.amazonaws.services.elasticbeanstalk.model.ApplicationDescription; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; public class ElasticBeanstalkLabelProvider extends ExplorerNodeLabelProvider { @Override public Image getDefaultImage(Object element) { ImageRegistry imageRegistry = ElasticBeanstalkPlugin.getDefault().getImageRegistry(); if ( element instanceof ElasticBeanstalkRootElement ) { return imageRegistry.get(ElasticBeanstalkPlugin.IMG_SERVICE); } if ( element instanceof ApplicationDescription ) { return imageRegistry.get(ElasticBeanstalkPlugin.IMG_APPLICATION); } if ( element instanceof EnvironmentDescription ) { return imageRegistry.get(ElasticBeanstalkPlugin.IMG_ENVIRONMENT); } return null; } @Override public String getText(Object element) { if ( element instanceof ElasticBeanstalkRootElement ) { return "AWS Elastic Beanstalk"; } if ( element instanceof ApplicationDescription ) { return ((ApplicationDescription) element).getApplicationName(); } if ( element instanceof EnvironmentDescription ) { return ((EnvironmentDescription) element).getEnvironmentName(); } return getExplorerNodeText(element); } }
7,373
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/CheckAccountRunnable.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.elasticbeanstalk.server.ui; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; public final class CheckAccountRunnable implements IRunnableWithProgress { private final AWSElasticBeanstalk client; public CheckAccountRunnable(AWSElasticBeanstalk client) { this.client = client; } @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { monitor.beginTask("Checking connection to AWS Elastic Beanstalk...", IProgressMonitor.UNKNOWN); client.listAvailableSolutionStacks(); client.describeEnvironments(); } finally { monitor.done(); } } }
7,374
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/DeployWizardApplicationSelectionPage.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.elasticbeanstalk.server.ui; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.core.databinding.observable.set.IObservableSet; import org.eclipse.core.databinding.observable.set.WritableSet; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.statushandlers.StatusManager; import org.eclipse.wst.server.ui.wizard.IWizardHandle; import org.eclipse.wst.server.ui.wizard.WizardFragment; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.core.ui.CancelableThread; import com.amazonaws.eclipse.databinding.BooleanValidator; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.DecorationChangeListener; import com.amazonaws.eclipse.databinding.NotInListValidator; import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants; import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin; import com.amazonaws.eclipse.elasticbeanstalk.deploy.DeployWizardDataModel; import com.amazonaws.eclipse.elasticbeanstalk.server.ui.databinding.ApplicationNameValidator; import com.amazonaws.eclipse.elasticbeanstalk.server.ui.databinding.EnvironmentNameValidator; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.ApplicationDescription; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentStatus; final class DeployWizardApplicationSelectionPage extends AbstractDeployWizardPage { private static final String LOADING = "Loading..."; private static final String NONE_FOUND = "None found"; private static final String VPC_CONFIGURATION_DOC_URL = "https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/vpc.html"; private DeployWizardVpcConfigurationPage vpcConfigPage; // Region controls private Combo regionCombo; private SelectionListener regionChangeListener; // Application controls private Button createNewApplicationRadioButton; private ISWTObservableValue createNewApplicationRadioButtonObservable; private Combo existingApplicationCombo; private Text newApplicationDescriptionText; private Text newApplicationNameText; private ControlDecoration newApplicationNameDecoration; private Button existingApplicationRadioButton; // Environment controls private ControlDecoration newEnvironmentNameDecoration; private Text newEnvironmentNameText; private Text newEnvironmentDescriptionText; private Combo environmentTypeCombo; private Button useNonDefaultVpcButton; private boolean useNonDefaultVpc = false; // Asynchronous workers private LoadApplicationsThread loadApplicationsThread; private LoadEnvironmentsThread loadEnvironmentsThread; private IObservableSet existingEnvironmentNames = new WritableSet(); private IObservableSet existingApplicationNames = new WritableSet(); private IObservableValue environmentNamesLoaded = new WritableValue(); private IObservableValue applicationNamesLoaded = new WritableValue(); private ISWTObservableValue newApplicationNameTextObservable; private ISWTObservableValue newApplicationDescriptionTextObservable; private ISWTObservableValue newEnvironmentDescriptionTextObservable; private ISWTObservableValue newEnvironmentNameTextObservable; private ISWTObservableValue environmentTypeComboObservable; private ISWTObservableValue useNonDefaultVpcButtonObservable; // Status of our connectivity to AWS Elastic Beanstalk private IStatus connectionStatus; private AWSElasticBeanstalk elasticBeanstalkClient; DeployWizardApplicationSelectionPage(DeployWizardDataModel wizardDataModel) { super(wizardDataModel); environmentNamesLoaded.setValue(false); applicationNamesLoaded.setValue(false); vpcConfigPage = new DeployWizardVpcConfigurationPage(wizardDataModel); } @Override public List<WizardFragment> getChildFragments() { List<WizardFragment> fragmentList = new ArrayList<>(); if (useNonDefaultVpc) { fragmentList.add(vpcConfigPage); } return fragmentList; } /* (non-Javadoc) * @see org.eclipse.wst.server.ui.wizard.WizardFragment#createComposite(org.eclipse.swt.widgets.Composite, org.eclipse.wst.server.ui.wizard.IWizardHandle) */ @Override public Composite createComposite(Composite parent, IWizardHandle handle) { wizardHandle = handle; elasticBeanstalkClient = AwsToolkitCore.getClientFactory().getElasticBeanstalkClientByEndpoint(wizardDataModel.getRegionEndpoint()); handle.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO)); handle.setMessage("", IStatus.OK); connectionStatus = testConnection(); if (connectionStatus.isOK()) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); createRegionSection(composite); createApplicationSection(composite); createEnvironmentSection(composite); createImportSection(composite); bindControls(); initializeDefaults(); return composite; } else { return new ErrorComposite(parent, SWT.NONE, connectionStatus); } } private IStatus testConnection() { try { wizardHandle.setMessage("", IStatus.OK); wizardHandle.run(true, false, new CheckAccountRunnable(elasticBeanstalkClient)); wizardHandle.setMessage("", IStatus.OK); return Status.OK_STATUS; } catch (InvocationTargetException ite) { String errorMessage = "Unable to connect to AWS Elastic Beanstalk. "; try { throw ite.getCause(); } catch (AmazonServiceException ase) { errorMessage += "Make sure you've registered your AWS account for the AWS Elastic Beanstalk service."; } catch (AmazonClientException ace) { errorMessage += "Make sure your computer is connected to the internet, and any network firewalls or proxys are configured appropriately."; } catch (Throwable t) {} return new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, errorMessage, ite.getCause()); } catch (InterruptedException e) { return Status.CANCEL_STATUS; } } /** * Initializes the page to its default selections */ private void initializeDefaults() { createNewApplicationRadioButtonObservable.setValue(true); existingApplicationRadioButton.setSelection(false); newApplicationNameTextObservable.setValue(""); newApplicationDescriptionTextObservable.setValue(""); newEnvironmentNameTextObservable.setValue(""); newEnvironmentDescriptionTextObservable.setValue(""); environmentTypeComboObservable.setValue(ConfigurationOptionConstants.LOAD_BALANCED_ENV); if (RegionUtils.isServiceSupportedInCurrentRegion(ServiceAbbreviations.BEANSTALK)) { regionCombo.setText(RegionUtils.getCurrentRegion().getName()); wizardDataModel.setRegion(RegionUtils.getCurrentRegion()); } else { regionCombo.setText(RegionUtils.getRegion(ElasticBeanstalkPlugin.DEFAULT_REGION).getName()); wizardDataModel.setRegion(RegionUtils.getRegion(ElasticBeanstalkPlugin.DEFAULT_REGION)); } regionChangeListener.widgetSelected(null); // Trigger the standard enabled / disabled control logic radioButtonSelected(createNewApplicationRadioButton); } private void createRegionSection(Composite composite) { Group regionGroup = newGroup(composite, "", 2); regionGroup.setLayout(new GridLayout(2, false)); newLabel(regionGroup, "Region:"); regionCombo = newCombo(regionGroup); for (Region region : RegionUtils.getRegionsForService(ServiceAbbreviations.BEANSTALK) ) { regionCombo.add(region.getName()); regionCombo.setData(region.getName(), region); } Region region = RegionUtils.getRegionByEndpoint(wizardDataModel.getRegionEndpoint()); regionCombo.setText(region.getName()); newFillingLabel(regionGroup, "AWS regions are geographically isolated, " + "allowing you to position your Elastic Beanstalk application closer to you or your customers.", 2); regionChangeListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { Region region = (Region)regionCombo.getData(regionCombo.getText()); String endpoint = region.getServiceEndpoints().get(ServiceAbbreviations.BEANSTALK); elasticBeanstalkClient = AwsToolkitCore.getClientFactory().getElasticBeanstalkClientByEndpoint(endpoint); wizardDataModel.setRegion(region); if (wizardDataModel.getKeyPairComposite() != null) { wizardDataModel.getKeyPairComposite().getKeyPairSelectionTable().setEc2RegionOverride(region); } createNewApplicationRadioButtonObservable.setValue(true); existingApplicationCombo.setEnabled(false); newApplicationNameText.setEnabled(true); newApplicationDescriptionText.setEnabled(true); refreshApplications(); refreshEnvironments(); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }; regionCombo.addSelectionListener(regionChangeListener); } private void createApplicationSection(Composite composite) { Group applicationGroup = newGroup(composite, "Application:", 2); applicationGroup.setLayout(new GridLayout(2, false)); createNewApplicationRadioButton = newRadioButton(applicationGroup, "Create a new application:", 2, true); createNewApplicationRadioButtonObservable = SWTObservables.observeSelection( createNewApplicationRadioButton); new NewApplicationOptionsComposite(applicationGroup); existingApplicationRadioButton = newRadioButton(applicationGroup, "Choose an existing application:", 1); existingApplicationCombo = newCombo(applicationGroup); existingApplicationCombo.setEnabled(false); } private void createEnvironmentSection(Composite composite) { Group environmentOptionsGroup = newGroup(composite, "Environment:", 2); environmentOptionsGroup.setLayout(new GridLayout(2, false)); new NewEnvironmentOptionsComposite(environmentOptionsGroup); } private void createImportSection(final Composite composite) { Hyperlink link = new Hyperlink(composite, SWT.None); link.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { ImportEnvironmentsWizard newWizard = new ImportEnvironmentsWizard(); WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), newWizard); dialog.open(); } }); link.setText("Import an existing environment into the Servers view"); link.setUnderlined(true); GridData layoutData = new GridData(); layoutData.horizontalSpan = 2; link.setLayoutData(layoutData); } private void bindControls() { super.initializeValidators(); newApplicationNameTextObservable = SWTObservables.observeText(newApplicationNameText, SWT.Modify); bindingContext.bindValue( newApplicationNameTextObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.NEW_APPLICATION_NAME), null, null); ChainValidator<String> applicationNameValidator = new ChainValidator<>( newApplicationNameTextObservable, createNewApplicationRadioButtonObservable, new ApplicationNameValidator(), new NotInListValidator<String>(existingApplicationNames, "Duplicate application name.")); bindingContext.addValidationStatusProvider(applicationNameValidator); bindingContext.addValidationStatusProvider(new ChainValidator<Boolean>(applicationNamesLoaded, new BooleanValidator("Appliction names not yet loaded"))); new DecorationChangeListener(newApplicationNameDecoration, applicationNameValidator.getValidationStatus()); newApplicationDescriptionTextObservable = SWTObservables.observeText(newApplicationDescriptionText, SWT.Modify); bindingContext.bindValue( newApplicationDescriptionTextObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.NEW_APPLICATION_DESCRIPTION), null, null); bindingContext.bindValue( createNewApplicationRadioButtonObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.CREATING_NEW_APPLICATION), null, null); // Existing application bindings bindingContext.bindValue(SWTObservables.observeSelection(existingApplicationCombo), PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.EXISTING_APPLICATION_NAME)); // New environment bindings newEnvironmentNameTextObservable = SWTObservables.observeText(newEnvironmentNameText, SWT.Modify); bindingContext.bindValue( newEnvironmentNameTextObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.NEW_ENVIRONMENT_NAME), null, null); newEnvironmentDescriptionTextObservable = SWTObservables.observeText(newEnvironmentDescriptionText, SWT.Modify); bindingContext.bindValue( newEnvironmentDescriptionTextObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.NEW_ENVIRONMENT_DESCRIPTION), null, null); ChainValidator<String> environmentNameValidator = new ChainValidator<>( newEnvironmentNameTextObservable, new EnvironmentNameValidator(), new NotInListValidator<String>(existingEnvironmentNames, "Duplicate environment name.")); bindingContext.addValidationStatusProvider(environmentNameValidator); bindingContext.addValidationStatusProvider(new ChainValidator<Boolean>(environmentNamesLoaded, new BooleanValidator("Environment names not yet loaded"))); new DecorationChangeListener(newEnvironmentNameDecoration, environmentNameValidator.getValidationStatus()); environmentTypeComboObservable = SWTObservables.observeSelection(environmentTypeCombo); bindingContext.bindValue( environmentTypeComboObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.ENVIRONMENT_TYPE)); useNonDefaultVpcButtonObservable = SWTObservables.observeSelection(useNonDefaultVpcButton); bindingContext.bindValue( useNonDefaultVpcButtonObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.USE_NON_DEFAULT_VPC)); } /** * Asynchronously updates the set of existing applications. Must be called * from the UI thread. */ private void refreshApplications() { /* * While the values load, we need to disable the controls and fake a * radio button selected event. */ createNewApplicationRadioButton.setSelection(true); existingApplicationRadioButton.setSelection(false); existingApplicationRadioButton.setEnabled(false); radioButtonSelected(createNewApplicationRadioButton); existingApplicationCombo.setItems(new String[] { LOADING }); existingApplicationCombo.select(0); cancelThread(loadApplicationsThread); applicationNamesLoaded.setValue(false); loadApplicationsThread = new LoadApplicationsThread(); loadApplicationsThread.start(); } /** * Safely cancels the thread given. */ private void cancelThread(CancelableThread thread) { if ( thread != null ) { synchronized (thread) { if ( thread.isRunning() ) { thread.cancel(); } } } } /** * Asynchronously updates the set of existing environments for the current * application. */ private void refreshEnvironments() { cancelThread(loadEnvironmentsThread); environmentNamesLoaded.setValue(false); loadEnvironmentsThread = new LoadEnvironmentsThread(); loadEnvironmentsThread.start(); } /** * We handle radio button selections by enabling and disabling various * controls. There are only two sources of these events that we care about. */ @Override protected void radioButtonSelected(Object source) { if ( source == existingApplicationRadioButton || source == createNewApplicationRadioButton) { boolean isCreatingNewApplication = (Boolean) createNewApplicationRadioButtonObservable.getValue(); existingApplicationCombo.setEnabled(!isCreatingNewApplication); newApplicationNameText.setEnabled(isCreatingNewApplication); newApplicationDescriptionText.setEnabled(isCreatingNewApplication); } } @Override public void enter() { super.enter(); if ( connectionStatus != null && connectionStatus.isOK() ) { refreshApplications(); refreshEnvironments(); } } /** * Cancel any outstanding work before exiting. */ @Override public void exit() { cancelThread(loadApplicationsThread); cancelThread(loadEnvironmentsThread); super.exit(); } private boolean isServiceSignUpException(Exception e) { if (e instanceof AmazonServiceException) { AmazonServiceException ase = (AmazonServiceException)e; return "OptInRequired".equalsIgnoreCase(ase.getErrorCode()); } return false; } private IStatus newServiceSignUpErrorStatus(Exception e) { return new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Error connecting to AWS Elastic Beanstalk. " + "Make sure you've signed up your AWS account for Elastic Beanstalk, and " + "waited for the changes to propagate.", e); } private class NewApplicationOptionsComposite extends Composite { public NewApplicationOptionsComposite(Composite parent) { super(parent, SWT.NONE); setLayout(new GridLayout(2, false)); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalIndent = 15; gridData.horizontalSpan = 2; setLayoutData(gridData); newLabel(this, "Name:"); newApplicationNameText = newText(this); newApplicationNameDecoration = newControlDecoration( newApplicationNameText, "Enter a new application name or select an existing application."); newLabel(this, "Description:"); newApplicationDescriptionText = newText(this); } } private class NewEnvironmentOptionsComposite extends Composite { public NewEnvironmentOptionsComposite(Composite parent) { super(parent, SWT.NONE); setLayout(new GridLayout(2, false)); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalIndent = 15; gridData.horizontalSpan = 2; setLayoutData(gridData); newLabel(this, "Name:"); newEnvironmentNameText = newText(this); newEnvironmentNameDecoration = newControlDecoration( newEnvironmentNameText, "Enter a new environment name"); newLabel(this, "Description:"); newEnvironmentDescriptionText = newText(this); final String[] items = { ConfigurationOptionConstants.SINGLE_INSTANCE_ENV, ConfigurationOptionConstants.LOAD_BALANCED_ENV, ConfigurationOptionConstants.WORKER_ENV }; newLabel(this, "Type:"); environmentTypeCombo = newCombo(this); environmentTypeCombo.setItems(items); useNonDefaultVpcButton = newCheckbox(parent, "", 1); useNonDefaultVpcButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { useNonDefaultVpc = useNonDefaultVpcButton.getSelection(); wizardHandle.update(); } }); createVpcSelectionLabel(parent); } } private void createVpcSelectionLabel(Composite composite) { adjustLinkLayout(newLink(composite, "Select the VPC to use when creating your environment. " + "<a href=\"" + VPC_CONFIGURATION_DOC_URL + "\">Learn more</a>"), 1); } private final class LoadApplicationsThread extends CancelableThread { @Override public void run() { final List<ApplicationDescription> applications = new ArrayList<>(); try { applications.addAll(elasticBeanstalkClient.describeApplications().getApplications()); } catch (Exception e) { if (isServiceSignUpException(e)) { StatusManager.getManager().handle(newServiceSignUpErrorStatus(e), StatusManager.SHOW | StatusManager.LOG); } else { Status status = new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to load existing applications: " + e.getMessage(), e); StatusManager.getManager().handle(status, StatusManager.LOG); } setRunning(false); return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { List<String> applicationNames = new ArrayList<>(); for ( ApplicationDescription application : applications ) { applicationNames.add(application.getApplicationName()); } Collections.sort(applicationNames); synchronized (LoadApplicationsThread.this) { if ( !isCanceled() ) { existingApplicationNames.clear(); existingApplicationNames.addAll(applicationNames); existingApplicationCombo.removeAll(); for ( String applicationName : applicationNames ) { existingApplicationCombo.add(applicationName); } if ( applications.size() > 0 ) { existingApplicationCombo.select(0); existingApplicationRadioButton.setEnabled(true); } else { existingApplicationCombo.setEnabled(false); existingApplicationRadioButton.setEnabled(false); createNewApplicationRadioButtonObservable.setValue(true); existingApplicationCombo.setItems(new String[] { NONE_FOUND}); existingApplicationCombo.select(0); } applicationNamesLoaded.setValue(true); runValidators(); } } } finally { setRunning(false); } } }); } } private final class LoadEnvironmentsThread extends CancelableThread { @Override public void run() { final List<EnvironmentDescription> environments = new ArrayList<>(); try { environments.addAll(elasticBeanstalkClient.describeEnvironments().getEnvironments()); } catch (Exception e) { if (isServiceSignUpException(e)) { StatusManager.getManager().handle(newServiceSignUpErrorStatus(e), StatusManager.SHOW | StatusManager.LOG); } else { Status status = new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to load existing environments: " + e.getMessage(), e); StatusManager.getManager().handle(status, StatusManager.LOG); } setRunning(false); return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { List<String> environmentNames = new ArrayList<>(); for ( EnvironmentDescription environment : environments ) { // Skip any terminated environments, since we can safely reuse their names if ( isEnvironmentTerminated(environment) ) { continue; } environmentNames.add(environment.getEnvironmentName()); } Collections.sort(environmentNames); synchronized (LoadEnvironmentsThread.this) { if ( !isCanceled() ) { existingEnvironmentNames.clear(); existingEnvironmentNames.addAll(environmentNames); environmentNamesLoaded.setValue(true); runValidators(); } } } finally { setRunning(false); } } }); } } private boolean isEnvironmentTerminated(EnvironmentDescription environment) { if (environment == null || environment.getStatus() == null) { return false; } try { EnvironmentStatus status = EnvironmentStatus.valueOf(environment.getStatus()); return (status == EnvironmentStatus.Terminated); } catch (Exception e) { return false; } } @Override public String getPageTitle() { return "Configure Application and Environment"; } @Override public String getPageDescription() { return "Choose a name for your application and environment"; } }
7,375
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/NoCredentialsConfiguredWizardFragment.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui; import org.eclipse.swt.widgets.Composite; import org.eclipse.wst.server.ui.wizard.IWizardHandle; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.elasticbeanstalk.NoCredentialsDialog; import com.amazonaws.eclipse.elasticbeanstalk.deploy.DeployWizardDataModel; public class NoCredentialsConfiguredWizardFragment extends AbstractDeployWizardPage { protected NoCredentialsConfiguredWizardFragment(DeployWizardDataModel wizardDataModel) { super(wizardDataModel); setComplete(false); } @Override public String getPageTitle() { return "No AWS security credentials configured"; } @Override public String getPageDescription() { return "No AWS security credentials configured"; } @Override public Composite createComposite(Composite parent, IWizardHandle handle) { wizardHandle = handle; handle.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry() .getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO)); return NoCredentialsDialog.createComposite(parent); } }
7,376
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/DeployWizardRoleSelectionPage.java
/* * Copyright 2015 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui; import java.util.ArrayList; import java.util.List; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.databinding.viewers.ViewersObservables; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Link; import org.eclipse.wst.server.ui.wizard.IWizardHandle; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.elasticbeanstalk.deploy.DeployWizardDataModel; import com.amazonaws.eclipse.elasticbeanstalk.jobs.LoadIamRolesJob; import com.amazonaws.eclipse.elasticbeanstalk.jobs.LoadResourcesCallback; import com.amazonaws.eclipse.elasticbeanstalk.util.BeanstalkConstants; import com.amazonaws.eclipse.elasticbeanstalk.util.OnUiThreadProxyFactory; import com.amazonaws.services.identitymanagement.model.Role; import com.amazonaws.util.StringUtils; public class DeployWizardRoleSelectionPage extends AbstractDeployWizardPage { public final RoleWidgetBuilder instanceRoleWidgetBuilder = new RoleWidgetBuilder() .withDefaultRole(BeanstalkConstants.DEFAULT_INSTANCE_ROLE_NAME) .withDataBindingFieldName(DeployWizardDataModel.INSTANCE_ROLE_NAME).withTrustEntity("ec2.amazonaws.com"); public final RoleWidgetBuilder serviceRoleWidgetBuilder = new RoleWidgetBuilder() .withDefaultRole(BeanstalkConstants.DEFAULT_SERVICE_ROLE_NAME) .withDataBindingFieldName(DeployWizardDataModel.SERVICE_ROLE_NAME) .withTrustEntity("beanstalk.amazonaws.com"); private static final String SERVICE_ROLE_LABEL_TEXT = "Service Role"; private static final String INSTANCE_PROFILE_ROLE_LABEL_TEXT = "Instance Profile Role"; private static final String SERVICE_ROLE_PERMISSIONS_DOC_URL = "https://docs.aws.amazon.com/console/elasticbeanstalk/roles"; private static final String IAM_ROLE_PERMISSIONS_DOC_URL = "http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.iam.roles.logs.html#iampolicy"; private Composite wizardPageRoot; private final LoadResourcesCallback<Role> loadIamRoleCallback; /** Only accessed through the UI thread. No need for synchronization **/ private boolean hasInsufficientIamPermissionDialogBeenShown; protected DeployWizardRoleSelectionPage(DeployWizardDataModel wizardDataModel) { super(wizardDataModel); // At this point the user can finish the wizard. All remaining pages are optional setComplete(true); this.loadIamRoleCallback = OnUiThreadProxyFactory.getProxy(LoadResourcesCallback.class, new LoadIamRolesCallback()); } @Override public String getPageTitle() { return "Permissions"; } @Override public String getPageDescription() { return "Select an instance profile and service role for your AWS Elastic Beanstalk environment"; } @Override public Composite createComposite(Composite parent, IWizardHandle handle) { this.hasInsufficientIamPermissionDialogBeenShown = false; wizardHandle = handle; setDefaultsInDataModel(); handle.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry() .getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO)); this.wizardPageRoot = new Composite(parent, SWT.NONE); wizardPageRoot.setLayout(new GridLayout(1, false)); initializeValidators(); new LoadIamRolesJob(loadIamRoleCallback).schedule(); return wizardPageRoot; } private class LoadIamRolesCallback implements LoadResourcesCallback<Role> { @Override public void onSuccess(List<Role> roles) { createRoleComboBoxControls(roles); } @Override public void onInsufficientPermissions() { if (!hasInsufficientIamPermissionDialogBeenShown) { hasInsufficientIamPermissionDialogBeenShown = true; IAMOperationNotAllowedErrorDialog dialog = new IAMOperationNotAllowedErrorDialog( Display.getDefault().getActiveShell()); int code = dialog.open(); if (code == IAMOperationNotAllowedErrorDialog.OK_BUTTON_CODE || code == IAMOperationNotAllowedErrorDialog.CLOSE) { new LoadIamRolesJob(loadIamRoleCallback).schedule(); } } else { createManualRoleControls(); } } // TODO When we fail to load IAM roles for reasons other then permissions issue then we should // probably throw an error dialog up. It may be that our logic for determining a service error // is a permissions failure has gotten stale and needs to be updated. Not entirely sure what the // experience for this should look like, hence the todo @Override public void onFailure() { onInsufficientPermissions(); } /** * If we do have IAM permissions we display the users roles in a dropdown to choose from */ private void createRoleComboBoxControls(List<Role> roles) { wizardDataModel.setSkipIamRoleAndInstanceProfileCreation(false); createInstanceProfileRoleLabel(wizardPageRoot); instanceRoleWidgetBuilder.setupComboViewer(wizardPageRoot, roles); newInstanceRoleDescLink(wizardPageRoot); createServiceRoleLabel(wizardPageRoot); serviceRoleWidgetBuilder.setupComboViewer(wizardPageRoot, roles); newServiceRoleDescLink(wizardPageRoot); // Redraw wizardPageRoot.layout(true); } /** * If we don't have IAM permissions to list roles then we display manual Text views that allow * users to manually specify the role. */ private void createManualRoleControls() { wizardDataModel.setSkipIamRoleAndInstanceProfileCreation(true); createInstanceProfileRoleLabel(wizardPageRoot); instanceRoleWidgetBuilder.setupManualControls(wizardPageRoot); newInstanceRoleDescLink(wizardPageRoot); createServiceRoleLabel(wizardPageRoot); serviceRoleWidgetBuilder.setupManualControls(wizardPageRoot); newServiceRoleDescLink(wizardPageRoot); // Redraw wizardPageRoot.layout(true); } private void createInstanceProfileRoleLabel(Composite composite) { newFillingLabel(composite, INSTANCE_PROFILE_ROLE_LABEL_TEXT); } private void createServiceRoleLabel(Composite composite) { newFillingLabel(composite, SERVICE_ROLE_LABEL_TEXT); } /** * Description and hyperlink for what the Instance Profile role is needed for */ private void newInstanceRoleDescLink(Composite composite) { adjustLinkLayout(newLink(composite, "If you choose not to use the default role, you must grant the relevant permissions to Elastic Beanstalk. " + "See the <a href=\"" + IAM_ROLE_PERMISSIONS_DOC_URL + "\">AWS Elastic Beanstalk Developer Guide</a> for more details.")); } /** * Description and hyperlink for what the Service role is needed for */ private void newServiceRoleDescLink(Composite composite) { adjustLinkLayout(newLink(composite, "A service role allows the Elastic Beanstalk service to monitor environment resources on your behalf. " + "See <a href=\"" + SERVICE_ROLE_PERMISSIONS_DOC_URL + "\">Service Roles, Instance Profiles, and User Policies</a> in the Elastic Beanstalk developer guide for details.")); } } /** * Set the default values for the roles and vpc in the data model to be reflected in the UI when the * model is bound to a control */ private void setDefaultsInDataModel() { if (StringUtils.isNullOrEmpty(wizardDataModel.getInstanceRoleName())) { wizardDataModel.setInstanceRoleName(BeanstalkConstants.DEFAULT_INSTANCE_ROLE_NAME); } if (StringUtils.isNullOrEmpty(wizardDataModel.getServiceRoleName())) { wizardDataModel.setServiceRoleName(BeanstalkConstants.DEFAULT_SERVICE_ROLE_NAME); } } /** * Class to hold data that differs between different role types (i.e. service role vs instance * role) and build appropriate widgets based on those differences */ private class RoleWidgetBuilder { private String defaultRole; private String dataBindingFieldName; private String trustEntity; public RoleWidgetBuilder withDefaultRole(String defaultRoleName) { this.defaultRole = defaultRoleName; return this; } public RoleWidgetBuilder withDataBindingFieldName(String dataBindingFieldName) { this.dataBindingFieldName = dataBindingFieldName; return this; } public RoleWidgetBuilder withTrustEntity(String trustEntity) { this.trustEntity = trustEntity; return this; } /** * Create the ComboViewer, setup databinding for it, and select the default role * * @param roles * List of IAM roles in the user's account */ public void setupComboViewer(Composite composite, List<Role> roles) { bindRoleComboView(newRoleComboView(composite, transformRoleList(roles)), dataBindingFieldName); } /** * Setup manual text controls when we don't have sufficient IAM permisisons to list roles so * user can still explicitly specify a role */ public void setupManualControls(Composite composite) { IObservableValue instanceRoleObservable = SWTObservables.observeText(newText(composite), SWT.Modify); getBindingContext().bindValue(instanceRoleObservable, PojoObservables.observeValue(wizardDataModel, dataBindingFieldName)); } /** * Setup data-binding for the ComboViewer * * @param comboViewer * @param fieldName * Field name in Data Model to bind to */ private void bindRoleComboView(ComboViewer comboViewer, String fieldName) { IObservableValue roleObservable = ViewersObservables.observeSingleSelection(comboViewer); IObservableValue observable = PojoObservables.observeValue(wizardDataModel, fieldName); getBindingContext().bindValue(roleObservable, observable); } private ComboViewer newRoleComboView(Composite composite, List<String> roles) { ComboViewer roleComboViewer = new ComboViewer(composite, SWT.DROP_DOWN | SWT.READ_ONLY); roleComboViewer.setContentProvider(ArrayContentProvider.getInstance()); roleComboViewer.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); roleComboViewer.setInput(roles); // Custom Label provider to clearly indicate the default role in the ComboViewer roleComboViewer.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { if (isDefaultRoleName(element)) { return "(Default) " + element; } return super.getText(element); } private boolean isDefaultRoleName(Object element) { return element instanceof String && defaultRole.equals(element); } }); return roleComboViewer; } /** * Transform the list of Role objects to a list of role names and filter out any roles that * don't have the required trust entity. Default role is always appended to the beginning of * the list (injected if it doesn't exist yet) * * @param roles * List of {@link Role} objects to transform * @return List of strings containing all role names that are appropriate for this role type */ private List<String> transformRoleList(List<Role> roles) { List<String> stringRoles = new ArrayList<>(roles.size() + 1); stringRoles.add(defaultRole); for (Role role : roles) { if (!isDefaultRole(role) && hasRequiredTrustEntity(role)) { stringRoles.add(role.getRoleName()); } } return stringRoles; } /** * We only display those roles that can be assumed by the appropriate entity. For instance * profile roles this is EC2, for the service role this is Beanstalk itself */ private boolean hasRequiredTrustEntity(Role role) { return role.getAssumeRolePolicyDocument().contains(trustEntity); } private boolean isDefaultRole(Role role) { return defaultRole.equals(role.getRoleName()); } /** * DataBindingContext is setup in {@link AbstractDeployWizardPage} * * @return The current data binding context */ private DataBindingContext getBindingContext() { return DeployWizardRoleSelectionPage.this.bindingContext; } } private void adjustLinkLayout(Link link) { adjustLinkLayout(link, 1); } }
7,377
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/DeployWizardVpcConfigurationPage.java
/* * Copyright 2010-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.elasticbeanstalk.server.ui; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.wst.server.ui.wizard.IWizardHandle; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants; import com.amazonaws.eclipse.elasticbeanstalk.deploy.DeployWizardDataModel; import com.amazonaws.eclipse.elasticbeanstalk.jobs.LoadResourcesCallback; import com.amazonaws.eclipse.elasticbeanstalk.jobs.LoadVpcsJob; import com.amazonaws.eclipse.elasticbeanstalk.util.BeanstalkConstants; import com.amazonaws.eclipse.elasticbeanstalk.util.OnUiThreadProxyFactory; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest; import com.amazonaws.services.ec2.model.DescribeSubnetsRequest; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.SecurityGroup; import com.amazonaws.services.ec2.model.Subnet; import com.amazonaws.services.ec2.model.Tag; import com.amazonaws.services.ec2.model.Vpc; import com.amazonaws.util.StringUtils; public class DeployWizardVpcConfigurationPage extends AbstractDeployWizardPage { private final VpcWidgetBuilder vpcWidgetBuilder = new VpcWidgetBuilder(); private static final String VPC_CONFIGURATION_DOC_URL = "https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/vpc.html"; private Composite wizardPageRoot; private final LoadResourcesCallback<Vpc> loadVpcCallback; protected DeployWizardVpcConfigurationPage( DeployWizardDataModel wizardDataModel) { super(wizardDataModel); setComplete(false); this.loadVpcCallback = OnUiThreadProxyFactory.getProxy( LoadResourcesCallback.class, new LoadVpcsCallback()); } @Override public String getPageTitle() { return "VPC Configuration"; } @Override public String getPageDescription() { return "Configure VPC and subnets for your EC2 instances, and specify VPC security group."; } // When entering this page, according to the setup from the previous page, // such as region and whether using non-default VPC, // the VPC list will be refreshed, and the availability for the UI // components will be refreshed as well. @Override public void enter() { super.enter(); if (wizardDataModel.isUseNonDefaultVpc()) { new LoadVpcsJob(wizardDataModel.getRegion(), loadVpcCallback).schedule(); } else { wizardDataModel.setVpcId(null); } // Set complete true since all the resources are loaded and selected default values. setComplete(true); } @Override public Composite createComposite(Composite parent, IWizardHandle handle) { wizardHandle = handle; setDefaultsInDataModel(); handle.setImageDescriptor(AwsToolkitCore.getDefault() .getImageRegistry() .getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO)); this.wizardPageRoot = new Composite(parent, SWT.NONE); wizardPageRoot.setLayout(new GridLayout(1, false)); initializeValidators(); vpcWidgetBuilder.buildVpcUiSection(wizardPageRoot); return wizardPageRoot; } private class LoadVpcsCallback implements LoadResourcesCallback<Vpc> { @Override public void onSuccess(List<Vpc> vpcs) { createVpcConfigurationSection(vpcs); } @Override public void onFailure() { onInsufficientPermissions(); } @Override public void onInsufficientPermissions() { // currently do nothing, and let the caller handle the failure. } private void createVpcConfigurationSection(List<Vpc> vpcs) { vpcWidgetBuilder.refreshVpcConfigurationSection(vpcs); vpcWidgetBuilder.refreshVpcSectionAvailability(); } } /** * Set the default values for the roles and vpc in the data model to be * reflected in the UI when the model is bound to a control */ private void setDefaultsInDataModel() { wizardDataModel.setAssociatePublicIpAddress(false); if (StringUtils.isNullOrEmpty(wizardDataModel.getElbScheme())) { wizardDataModel .setElbScheme(BeanstalkConstants.ELB_SCHEME_EXTERNAL); } } private enum CheckboxType { ELB, EC2 } private class VpcWidgetBuilder { private final String[] SUBNET_TABLE_TITLES = { "Availability Zone", "Subnet ID", "Cidr Block", "ELB", "EC2" }; private final String[] ELB_SCHEMES = { BeanstalkConstants.ELB_SCHEME_EXTERNAL, BeanstalkConstants.ELB_SCHEME_INTERNAL }; private Combo vpcCombo; private Table subnetsTable; private Button apiaButton;// Associate Public Ip Address private Combo securityGroupCombo; private Combo elbSchemeCombo; private List<Button> checkboxButtons = new ArrayList<>(); // build UI section only, not populating data public void buildVpcUiSection(Composite composite) { Composite group = newGroup(composite, "VPC Configuration:"); group.setLayout(new GridLayout(3, false)); createVpcSelectionSection(group); vpcCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onVpcSelectionChanged(); } }); apiaButton = newCheckbox(group, "Associate Public IP Address", 1); bindAssociatePublicIpAddressButton(apiaButton); createSubnetSelectionSection(group); createSecurityGroupSelection(group); securityGroupCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { onSecurityGroupSelectionChanged(); } }); createElbSchemesSelectionSection(group); bindCombo(elbSchemeCombo, DeployWizardDataModel.ELB_SCHEME); } private void onCheckboxSelected(String subnetId, CheckboxType type, boolean selected) { Set<String> subnets; switch(type) { case EC2: subnets = wizardDataModel.getEc2Subnets(); break; case ELB: subnets = wizardDataModel.getElbSubnets(); break; default: subnets = new HashSet<>(); } if (selected) { subnets.add(subnetId); } else { subnets.remove(subnetId); } } public void refreshVpcSectionAvailability() { vpcCombo.setEnabled(wizardDataModel.isUseNonDefaultVpc()); subnetsTable.setEnabled(wizardDataModel.isUseNonDefaultVpc()); apiaButton.setEnabled(wizardDataModel.isUseNonDefaultVpc()); elbSchemeCombo.setEnabled(wizardDataModel.isUseNonDefaultVpc() && ConfigurationOptionConstants.LOAD_BALANCED_ENV .equals(wizardDataModel.getEnvironmentType())); } private void createSubnetSelectionSection(Composite composite) { createSubnetsSelectionLabel(composite); createSubnetsTable(composite); } private void createElbSchemesSelectionSection(Composite parent) { newLabel(parent, "ELB visibility: ", 1) .setToolTipText("This combo box is only enabled when you are selecting Load Balanced Web Server Environment type."); elbSchemeCombo = newCombo(parent, 1); elbSchemeCombo.setItems(ELB_SCHEMES); newLabel(parent, "Select Internal when load balancing a back-end\nservice that should not be publicly available.", 1, SWT.LEFT, SWT.BOTTOM); } private void createSecurityGroupSelection(Composite parent) { newLabel(parent, "VPC security group:"); securityGroupCombo = newCombo(parent, 2); } public void refreshVpcConfigurationSection(List<Vpc> vpcs) { List<String> vpcsString = transformVpcList(vpcs); vpcCombo.setItems(new String[]{}); for (int i = 0; i < vpcsString.size(); ++i) { vpcCombo.add(vpcsString.get(i)); vpcCombo.setData(vpcsString.get(i), vpcs.get(i)); } if (!vpcs.isEmpty()) { vpcCombo.select(0); } onVpcSelectionChanged(); } private void createVpcSelectionSection(Composite composite) { createVpcSelectionLabel(composite); newLabel(composite, "VPC:"); vpcCombo = newCombo(composite); } private void createVpcSelectionLabel(Composite composite) { adjustLinkLayout( newLink(composite, "Select the VPC to use when creating your environment. " + "<a href=\"" + VPC_CONFIGURATION_DOC_URL + "\">Learn more</a>."), 3); } private void bindAssociatePublicIpAddressButton(Button button) { IObservableValue apiaObservable = SWTObservables .observeSelection(button); IObservableValue observable = PojoObservables.observeValue( wizardDataModel, DeployWizardDataModel.ASSOCIATE_PUBLIC_IP_ADDRESS); getBindingContext().bindValue(apiaObservable, observable); } private void createSubnetsSelectionLabel(Composite composite) { newLabel( composite, "Select different subnets for ELB and EC2 instances in your Availability Zone.", 3); } private void createSubnetsTable(Composite composite) { subnetsTable = new Table(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); subnetsTable.setLinesVisible(true); subnetsTable.setHeaderVisible(true); TableLayout layout = new TableLayout(); for (int i = 0; i < SUBNET_TABLE_TITLES.length; ++i) { TableColumn column = new TableColumn(subnetsTable, SWT.NONE); column.setText(SUBNET_TABLE_TITLES[i]); layout.addColumnData(new ColumnWeightData(100)); } GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.heightHint = 100; data.widthHint = 200; data.horizontalSpan = 5; subnetsTable.setLayoutData(data); subnetsTable.setLayout(layout); } private void onVpcSelectionChanged() { Vpc selectedVpc = (Vpc)vpcCombo.getData(vpcCombo.getItem(vpcCombo.getSelectionIndex())); // Reset Data Model wizardDataModel.setVpcId(selectedVpc.getVpcId()); wizardDataModel.getEc2Subnets().clear(); wizardDataModel.getElbSubnets().clear(); // Redraw Subnet table UI subnetsTable.removeAll(); for (Button button : checkboxButtons) { if (button != null) button.dispose(); } AmazonEC2 ec2 = AwsToolkitCore.getClientFactory() .getEC2ClientByEndpoint( wizardDataModel.getRegion().getServiceEndpoint( ServiceAbbreviations.EC2)); List<Subnet> subnets = ec2.describeSubnets( new DescribeSubnetsRequest().withFilters(new Filter() .withName("vpc-id").withValues( wizardDataModel.getVpcId()))).getSubnets(); for (int i = 0; i < subnets.size(); ++i) { TableItem item = new TableItem(subnetsTable, SWT.CENTER); final Subnet subnet = subnets.get(i); item.setText(0, subnet.getAvailabilityZone()); item.setText(1, subnet.getSubnetId()); item.setText(2, subnet.getCidrBlock()); checkboxButtons.add(drawCheckboxOnSubnetTable(item, subnet.getSubnetId(), 3, CheckboxType.ELB, wizardDataModel.isUseNonDefaultVpc() && ConfigurationOptionConstants.LOAD_BALANCED_ENV.equals(wizardDataModel.getEnvironmentType()))); checkboxButtons.add(drawCheckboxOnSubnetTable(item, subnet.getSubnetId(), 4, CheckboxType.EC2, true)); } // Redraw security group UI List<SecurityGroup> securityGroups = ec2.describeSecurityGroups(new DescribeSecurityGroupsRequest() .withFilters(new Filter() .withName("vpc-id").withValues(wizardDataModel.getVpcId()))).getSecurityGroups(); securityGroupCombo.removeAll(); for (SecurityGroup securityGroup : securityGroups) { String securityGroupText = securityGroup.getGroupName() + " -- " + securityGroup.getGroupId(); securityGroupCombo.add(securityGroupText); securityGroupCombo.setData(securityGroupText, securityGroup); } securityGroupCombo.select(0); onSecurityGroupSelectionChanged(); } private void onSecurityGroupSelectionChanged() { SecurityGroup securityGroup = (SecurityGroup) securityGroupCombo.getData( securityGroupCombo.getItem(securityGroupCombo.getSelectionIndex())); wizardDataModel.setSecurityGroup(securityGroup.getGroupId()); } private Button drawCheckboxOnSubnetTable(TableItem item, final String subnetId, int columnIndex, final CheckboxType type, final boolean enabled) { TableEditor editor = new TableEditor(subnetsTable); Button checkbox = new Button(subnetsTable, SWT.CHECK); checkbox.setEnabled(enabled); checkbox.pack(); editor.minimumWidth = checkbox.getSize().x; editor.horizontalAlignment = SWT.LEFT; editor.setEditor(checkbox, item, columnIndex); checkbox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onCheckboxSelected(subnetId, type, ((Button)e.getSource()).getSelection()); } }); return checkbox; } private void bindCombo(Combo combo, String fieldName) { IObservableValue comboObservable = SWTObservables .observeSelection(combo); IObservableValue pojoObservable = PojoObservables.observeValue( wizardDataModel, fieldName); getBindingContext().bindValue(comboObservable, pojoObservable); } private List<String> transformVpcList(List<Vpc> vpcs) { List<String> stringVpcs = new ArrayList<>(vpcs.size()); for (Vpc vpc : vpcs) { String vpcTextPrefix = getVpcName(vpc); if (!StringUtils.isNullOrEmpty(vpcTextPrefix)) { vpcTextPrefix += " -- "; } stringVpcs.add(vpcTextPrefix + vpc.getVpcId()); } return stringVpcs; } private String getVpcName(Vpc vpc) { if (vpc.getTags() != null && !vpc.getTags().isEmpty()) { for (Tag tag : vpc.getTags()) { if ("Name".equals(tag.getKey())) { return tag.getValue(); } } } return ""; } /** * DataBindingContext is setup in {@link AbstractDeployWizardPage} * * @return The current data binding context */ private DataBindingContext getBindingContext() { return DeployWizardVpcConfigurationPage.this.bindingContext; } } }
7,378
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/ServerDefaultsUtils.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui; import java.util.HashSet; import java.util.Set; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.IServerWorkingCopy; import org.eclipse.wst.server.core.ServerCore; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; /** * Utilities for initializing default values for new server instances. */ public class ServerDefaultsUtils { public static void setDefaultServerName(IServerWorkingCopy serverWorkingCopy, String environmentName) { Set<String> existingServerNames = new HashSet<>(); for (IServer server : ServerCore.getServers()) { existingServerNames.add(server.getName()); } String host = serverWorkingCopy.getHost(); String newServerName = environmentName + " at " + host; int count = 1; while (existingServerNames.contains(newServerName)) { newServerName = environmentName + " (" + count++ + ") " + "at " + serverWorkingCopy.getHost(); } serverWorkingCopy.setName(newServerName); } public static void setDefaultHostName(IServerWorkingCopy serverWorkingCopy, String regionEndpoint) { Region region = RegionUtils.getRegionByEndpoint(regionEndpoint); String regionName = region.getName(); serverWorkingCopy.setHost("AWS Elastic Beanstalk - " + regionName); } }
7,379
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/LaunchConfigurationTabGroup.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui; import org.eclipse.debug.ui.AbstractLaunchConfigurationTabGroup; import org.eclipse.debug.ui.ILaunchConfigurationDialog; import org.eclipse.debug.ui.ILaunchConfigurationTab; import org.eclipse.wst.server.ui.ServerLaunchConfigurationTab; import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin; public class LaunchConfigurationTabGroup extends AbstractLaunchConfigurationTabGroup { @Override public void createTabs(ILaunchConfigurationDialog dialog, String mode) { ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[1]; tabs[0] = new ServerLaunchConfigurationTab(new String[] { ElasticBeanstalkPlugin.TOMCAT_6_SERVER_TYPE_ID, ElasticBeanstalkPlugin.TOMCAT_7_SERVER_TYPE_ID }); tabs[0].setLaunchConfigurationDialog(dialog); setTabs(tabs); } }
7,380
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/IAMOperationNotAllowedErrorDialog.java
/* * Copyright 2010-2014 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.elasticbeanstalk.server.ui; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.elasticbeanstalk.resources.BeanstalkResourceProvider; /** * The dialog to show if the current user doens't have sufficient permission to perform * iam:listRoles when configuring the IAM role for a new Beanstalk environment. */ public class IAMOperationNotAllowedErrorDialog extends MessageDialog { public static final int OK_BUTTON_CODE = 0; public static final int CLOSE = -1; private static final String TITLE = "IAM operation not allowed"; private static final String IMAGE_NAME = AwsToolkitCore.IMAGE_AWS_ICON; private final BeanstalkResourceProvider resourceProvider = new BeanstalkResourceProvider(); private static final String MESSAGE = "The current IAM user does not have permissions to list IAM roles or create instance profiles. " + "If these permissions are not granted to the current user all IAM related configuration will " + "have to be entered manually and the Toolkit will be unable to create the required resources " + "on your behalf."; public IAMOperationNotAllowedErrorDialog(Shell parentShell) { super(parentShell, TITLE, AwsToolkitCore.getDefault().getImageRegistry().get(IMAGE_NAME), MESSAGE, MessageDialog.WARNING, new String[] { "OK" }, OK_BUTTON_CODE); } @Override public Control createCustomArea(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(1, false); layout.verticalSpacing = 15; layout.marginBottom = 15; composite.setLayout(layout); Group addPermissionsInstructionsGruop = displayPermissionsInstructions(composite); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.widthHint = 650; addPermissionsInstructionsGruop.setLayoutData(gridData); return composite; } private Group displayPermissionsInstructions(final Composite parent) { Group group = new Group(parent, SWT.BORDER); group.setText("To grant the needed permissions do the following"); group.setLayout(new GridLayout(1, false)); Label label = new Label(group, SWT.WRAP); label.setText(String.format(getInstructionsText())); label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); return group; } private String getInstructionsText() { return "(1) Open up a browser and log into the IAM Management Console (https://console.aws.amazon.com/iam/home) using your admin account.%n" + "(2) Go to users%n" + "(3) Select the user that the toolkit is configured to use%n" + "(4) Modify the existing policy to allow access to IAM actions or add a new policy granting the needed permissions.%n" + " - The IAMFullAccess Managed Policy has the needed permissions.%n" + " - Alternatively you can create an inline policy granting the minimum permissions required with the following content:%n" + resourceProvider.getMinimumIamPermissionsPolicy().asString(); } }
7,381
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/ImportEnvironmentsWizard.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.elasticbeanstalk.server.ui; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.wst.server.core.IServer; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; 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.elasticbeanstalk.ElasticBeanstalkPlugin; import com.amazonaws.eclipse.elasticbeanstalk.NoCredentialsDialog; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentStatus; /** * Wizard that allows the user to select running AWS Elastic Beanstalk environments to import into * the servers view. */ public class ImportEnvironmentsWizard extends Wizard { private CheckboxTreeViewer viewer; private static final int COL_ENV_NAME = 0; private static final int COL_APPLICATION_NAME = 1; private static final int COL_DATE = 2; private static final int COL_STATUS = 3; private static final int COL_REGION = 4; private static final int NUM_COLS = 5; /* * Environments to import, cast as Objects to interface easily with jface. */ private Object[] toImport = null; public ImportEnvironmentsWizard() { super(); setWindowTitle("Import environments into the Servers view"); setHelpAvailable(false); } private static final class RegionEnvironmentDescription { private final Region region; private final EnvironmentDescription environmentDescription; public RegionEnvironmentDescription(Region region, EnvironmentDescription environmentDescription) { this.region = region; this.environmentDescription = environmentDescription; } } /** * Our single page is responsible for creating the controls. */ private class ImportPage extends WizardPage { private static final String MESSAGE = "Choose the environments to import."; protected ImportPage() { super("Import environments", MESSAGE, AwsToolkitCore .getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO)); } @Override public void createControl(Composite container) { if ( !AwsToolkitCore.getDefault().getAccountInfo().isValid() ) { setControl(NoCredentialsDialog.createComposite(container)); return; } IStatus status = testConnection(); if ( !status.isOK() ) { setControl(new ErrorComposite(container, SWT.None, status)); return; } Composite parent = new Composite(container, SWT.None); FillLayout layout = new FillLayout(SWT.VERTICAL); parent.setLayout(layout); /* * Determine which elastic beanstalk environments aren't already imported as servers */ List<RegionEnvironmentDescription> environmentsToImport = new LinkedList<>(); for ( Region region : RegionUtils.getRegionsForService(ServiceAbbreviations.BEANSTALK) ) { List<EnvironmentDescription> elasticBeanstalkEnvs = getExistingEnvironments(region); Collection<IServer> elasticBeanstalkServers = ElasticBeanstalkPlugin .getExistingElasticBeanstalkServers(); for ( EnvironmentDescription env : elasticBeanstalkEnvs ) { boolean alreadyExists = false; for ( IServer server : elasticBeanstalkServers ) { if ( ElasticBeanstalkPlugin.environmentsSame(env, region, server) ) { alreadyExists = true; break; } } if ( !alreadyExists ) { environmentsToImport.add(new RegionEnvironmentDescription(region, env)); } } } if ( environmentsToImport.isEmpty() ) { new Label(parent, SWT.None).setText("There are no running environments to import."); } else { Composite treeContainer = new Composite(parent, SWT.None); treeContainer.setLayout(new TreeColumnLayout()); int style = SWT.V_SCROLL | SWT.BORDER | SWT.SINGLE; viewer = new CheckboxTreeViewer(treeContainer, style); viewer.getTree().setLinesVisible(true); viewer.getTree().setHeaderVisible(true); EnvironmentSelectionTreeProvider labelProvider = new EnvironmentSelectionTreeProvider(); viewer.setContentProvider(labelProvider); viewer.setLabelProvider(labelProvider); for ( int i = 0; i < NUM_COLS; i++ ) { switch (i) { case COL_ENV_NAME: newColumn("Environment name", 10); break; case COL_APPLICATION_NAME: newColumn("Application name", 10); break; case COL_DATE: newColumn("Last updated", 10); break; case COL_STATUS: newColumn("Status", 10); break; case COL_REGION: newColumn("Region", 10); break; } } viewer.setInput(environmentsToImport.toArray(new RegionEnvironmentDescription[environmentsToImport.size()])); viewer.getTree().addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if ( viewer.getCheckedElements().length > 0 ) { setErrorMessage(null); setMessage(MESSAGE); toImport = viewer.getCheckedElements(); } else { setErrorMessage("Select at least one environment to import"); toImport = null; } ImportEnvironmentsWizard.this.getContainer().updateButtons(); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); } setControl(container); } private IStatus testConnection() { try { this.getWizard() .getContainer() .run(true, false, new CheckAccountRunnable(AwsToolkitCore.getClientFactory() .getElasticBeanstalkClientByEndpoint( RegionUtils.getRegion(ElasticBeanstalkPlugin.DEFAULT_REGION) .getServiceEndpoints().get(ServiceAbbreviations.BEANSTALK)))); return Status.OK_STATUS; } catch ( InvocationTargetException ite ) { String errorMessage = "Unable to connect to AWS Elastic Beanstalk. "; try { throw ite.getCause(); } catch ( AmazonServiceException ase ) { errorMessage += "Make sure you've registered your AWS account for the AWS Elastic Beanstalk service."; } catch ( AmazonClientException ace ) { errorMessage += "Make sure your computer is connected to the internet, and any network firewalls or proxys are configured appropriately."; } catch ( Throwable t ) { } return new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, errorMessage, ite.getCause()); } catch ( InterruptedException e ) { return Status.CANCEL_STATUS; } } } @Override public void addPages() { addPage(new ImportPage()); } /** * Returns all AWS Elastic Beanstalk environments in the region given. */ private List<EnvironmentDescription> getExistingEnvironments(Region region) { List<EnvironmentDescription> filtered = new ArrayList<>(); AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory().getElasticBeanstalkClientByEndpoint( region.getServiceEndpoints().get(ServiceAbbreviations.BEANSTALK)); List<EnvironmentDescription> environments = client.describeEnvironments().getEnvironments(); // Only list the active environments for ( EnvironmentDescription env : environments ) { if ( !(env.getStatus().equals(EnvironmentStatus.Terminated.toString()) || env.getStatus().equals( EnvironmentStatus.Terminating.toString())) ) filtered.add(env); } return filtered; } /* * (non-Javadoc) * * @see org.eclipse.jface.wizard.Wizard#performFinish() */ @Override public boolean performFinish() { try { getContainer().run(true, false, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Importing servers", toImport.length * 3); try { for ( Object elasticBeanstalkEnv : toImport ) { try { RegionEnvironmentDescription regionEnvironmentDescription = (RegionEnvironmentDescription) elasticBeanstalkEnv; ElasticBeanstalkPlugin.importEnvironment( regionEnvironmentDescription.environmentDescription, regionEnvironmentDescription.region, monitor); } catch ( CoreException e ) { throw new RuntimeException(e); } } } finally { monitor.done(); } } }); } catch ( Exception e ) { throw new RuntimeException(e); } return true; } @Override public boolean needsProgressMonitor() { return true; } @Override public boolean canFinish() { return toImport != null; } protected TreeColumn newColumn(String columnText, int weight) { Tree table = viewer.getTree(); TreeColumn column = new TreeColumn(table, SWT.NONE); column.setText(columnText); TreeColumnLayout tableColumnLayout = (TreeColumnLayout) viewer.getTree().getParent().getLayout(); if ( tableColumnLayout == null ) tableColumnLayout = new TreeColumnLayout(); tableColumnLayout.setColumnData(column, new ColumnWeightData(weight)); viewer.getTree().getParent().setLayout(tableColumnLayout); return column; } private class EnvironmentSelectionTreeProvider implements ITableLabelProvider, ITreeContentProvider { @Override public void removeListener(ILabelProviderListener listener) { } @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public void dispose() { } @Override public void addListener(ILabelProviderListener listener) { } @Override public String getColumnText(Object element, int columnIndex) { RegionEnvironmentDescription env = (RegionEnvironmentDescription) element; switch (columnIndex) { case COL_ENV_NAME: return env.environmentDescription.getEnvironmentName(); case COL_APPLICATION_NAME: return env.environmentDescription.getApplicationName(); case COL_DATE: return env.environmentDescription.getDateUpdated().toString(); case COL_STATUS: return env.environmentDescription.getStatus(); case COL_REGION: return env.region.getName(); } return ""; } @Override public Image getColumnImage(Object element, int columnIndex) { if ( columnIndex == 0 ) return ElasticBeanstalkPlugin.getDefault().getImageRegistry().get(ElasticBeanstalkPlugin.IMG_SERVER); return null; } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Override public boolean hasChildren(Object element) { return false; } @Override public Object getParent(Object element) { return null; } @Override public Object[] getElements(Object inputElement) { return (Object[]) inputElement; } @Override public Object[] getChildren(Object parentElement) { return new Object[0]; } } }
7,382
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/ErrorComposite.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.elasticbeanstalk.server.ui; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.forms.widgets.TableWrapLayout; final class ErrorComposite extends Composite { ErrorComposite(Composite parent, int style, IStatus connectionStatus) { super(parent, style); TableWrapLayout layout = new TableWrapLayout(); layout.numColumns = 1; setLayout(layout); new Label(this, SWT.WRAP).setText(connectionStatus.getMessage()); } }
7,383
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/DeployWizard.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.wst.server.core.IServerWorkingCopy; import org.eclipse.wst.server.core.TaskModel; import org.eclipse.wst.server.ui.wizard.WizardFragment; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants; import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin; import com.amazonaws.eclipse.elasticbeanstalk.Environment; import com.amazonaws.eclipse.elasticbeanstalk.deploy.DeployWizardDataModel; import com.amazonaws.eclipse.elasticbeanstalk.solutionstacks.SolutionStacks; public class DeployWizard extends WizardFragment { private static final Logger logger = Logger.getLogger(WizardFragment.class.getName()); private DeployWizardApplicationSelectionPage applicationSelectionPage; private DeployWizardEnvironmentConfigPage releaseDetailsPage; private DeployWizardRoleSelectionPage roleSelectionPage; private NoCredentialsConfiguredWizardFragment noCredentialsConfiguredWizardFragment; private final DeployWizardDataModel wizardDataModel = new DeployWizardDataModel(); public static final String DEPLOY_WIZARD_DIALOG_SETTINGS_SECTION = "deployWizardDialogSettingsSection"; public static final String DEPLOY_WIZARD_APPLICATION_NAME_SETTING = "deployWizardApplicationNameSetting"; public static final String DEPLOY_WIZARD_ENVIRONMENT_NAME_SETTING = "deployWizardEnvironmentNameSetting"; public static final String DEPLOY_WIZARD_S3_BUCKET_SETTING = "deployWizardS3BucketSetting"; public static final String DEPLOY_WIZARD_REGION_ENDPOINT_SETTING = "deployWizardRegionEndpoint"; public DeployWizard() { applicationSelectionPage = new DeployWizardApplicationSelectionPage(wizardDataModel); roleSelectionPage = new DeployWizardRoleSelectionPage(wizardDataModel); releaseDetailsPage = new DeployWizardEnvironmentConfigPage(wizardDataModel); noCredentialsConfiguredWizardFragment = new NoCredentialsConfiguredWizardFragment(wizardDataModel); IDialogSettings globalDialogSettings = ElasticBeanstalkPlugin.getDefault().getDialogSettings(); IDialogSettings deployWizardSection = globalDialogSettings.getSection(DEPLOY_WIZARD_DIALOG_SETTINGS_SECTION); if (deployWizardSection == null) { deployWizardSection = globalDialogSettings.addNewSection(DEPLOY_WIZARD_DIALOG_SETTINGS_SECTION); } if ( RegionUtils.isServiceSupportedInCurrentRegion(ServiceAbbreviations.BEANSTALK) ) { wizardDataModel.setRegion(RegionUtils.getCurrentRegion()); } else { wizardDataModel.setRegion(RegionUtils.getRegion(ElasticBeanstalkPlugin.DEFAULT_REGION)); } } @Override @SuppressWarnings("rawtypes") public List getChildFragments() { List<WizardFragment> list = new ArrayList<>(); if (AwsToolkitCore.getDefault().getAccountInfo().isValid()) { list.add(applicationSelectionPage); list.add(roleSelectionPage); list.add(releaseDetailsPage); } else { list.add(noCredentialsConfiguredWizardFragment); } return list; } @Override public boolean isComplete() { @SuppressWarnings("unchecked") List<WizardFragment> childFragments = getChildFragments(); for (WizardFragment fragment : childFragments) { if (fragment.isComplete() == false) { return false; } } return true; } @Override public void enter() { IServerWorkingCopy runtime = (IServerWorkingCopy)getTaskModel().getObject(TaskModel.TASK_SERVER); if (runtime == null) { logger.warning("null server working copy"); return; } } @Override public void performFinish(IProgressMonitor monitor) throws CoreException { IServerWorkingCopy serverWorkingCopy = (IServerWorkingCopy) getTaskModel().getObject(TaskModel.TASK_SERVER); ServerDefaultsUtils.setDefaultHostName(serverWorkingCopy, wizardDataModel.getRegionEndpoint()); ServerDefaultsUtils.setDefaultServerName(serverWorkingCopy, wizardDataModel.getEnvironmentName()); Environment environment = (Environment)serverWorkingCopy.loadAdapter(Environment.class, monitor); environment.setApplicationName(wizardDataModel.getApplicationName()); environment.setApplicationDescription(wizardDataModel.getNewApplicationDescription()); environment.setEnvironmentName(wizardDataModel.getEnvironmentName()); // Environment type is overloaded in the UI to cover both tier and // type; separate them out here. if (ConfigurationOptionConstants.WORKER_ENV.equals(wizardDataModel.getEnvironmentType())) { environment.setEnvironmentTier(ConfigurationOptionConstants.WORKER); environment.setEnvironmentType(ConfigurationOptionConstants.LOAD_BALANCED_ENV); } else { environment.setEnvironmentTier(ConfigurationOptionConstants.WEB_SERVER); environment.setEnvironmentType(wizardDataModel.getEnvironmentType()); } environment.setEnvironmentDescription(wizardDataModel.getNewEnvironmentDescription()); environment.setRegionId(wizardDataModel.getRegion().getId()); environment.setHealthCheckUrl(wizardDataModel.getHealthCheckUrl()); environment.setSslCertificateId(wizardDataModel.getSslCertificateId()); environment.setSnsEndpoint(wizardDataModel.getSnsEndpoint()); environment.setAccountId(AwsToolkitCore.getDefault().getCurrentAccountId()); environment.setIncrementalDeployment(wizardDataModel.isIncrementalDeployment()); environment.setWorkerQueueUrl(wizardDataModel.getWorkerQueueUrl()); environment.setSkipIamRoleAndInstanceProfileCreation(wizardDataModel.isSkipIamRoleAndInstanceProfileCreation()); environment.setInstanceRoleName(wizardDataModel.getInstanceRoleName()); environment.setServiceRoleName(wizardDataModel.getServiceRoleName()); environment.setVpcId(wizardDataModel.getVpcId()); String ec2Subnets = Environment.catSubnetList(wizardDataModel.getEc2Subnets()); String elbSubnets = Environment.catSubnetList(wizardDataModel.getElbSubnets()); environment.setSubnets(ec2Subnets); if (ConfigurationOptionConstants.LOAD_BALANCED_ENV.equals(wizardDataModel.getEnvironmentType())) { environment.setElbSubnets(elbSubnets); environment.setElbScheme(wizardDataModel.getElbScheme()); } environment.setAssociatePublicIpAddress(wizardDataModel.isAssociatePublicIpAddress()); if ( wizardDataModel.isUsingCname() ) { environment.setCname(wizardDataModel.getCname()); } if ( wizardDataModel.isUsingKeyPair() && wizardDataModel.getKeyPair() != null ) { environment.setKeyPairName(wizardDataModel.getKeyPair().getKeyName()); } String serverTypeId = serverWorkingCopy.getServerType().getId(); environment.setSolutionStack(SolutionStacks.lookupSolutionStackByServerTypeId(serverTypeId)); } }
7,384
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/DeployWizardEnvironmentConfigPage.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.elasticbeanstalk.server.ui; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.databinding.viewers.IViewerObservableValue; import org.eclipse.jface.databinding.viewers.ViewersObservables; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.wst.server.ui.wizard.IWizardHandle; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.DecorationChangeListener; import com.amazonaws.eclipse.databinding.NotEmptyValidator; import com.amazonaws.eclipse.ec2.databinding.ValidKeyPairValidator; import com.amazonaws.eclipse.ec2.ui.keypair.KeyPairComposite; import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants; import com.amazonaws.eclipse.elasticbeanstalk.deploy.DeployWizardDataModel; import com.amazonaws.eclipse.elasticbeanstalk.server.ui.databinding.NoInvalidNameCharactersValidator; class DeployWizardEnvironmentConfigPage extends AbstractDeployWizardPage { private KeyPairComposite keyPairComposite; private Button usingCnameButton; private Text cname; private Button usingKeyPair; private Button incrementalDeploymentButton; private Text healthCheckText; private Text workerQueueUrlText; private ISWTObservableValue usingKeyPairObservable; private ISWTObservableValue usingCnameObservable; private ISWTObservableValue healthCheckURLObservable; private ISWTObservableValue sslCertObservable; private ISWTObservableValue snsTopicObservable; private ISWTObservableValue workerQueueUrlObservable; public DeployWizardEnvironmentConfigPage(DeployWizardDataModel wizardDataModel) { super(wizardDataModel); } @Override public Composite createComposite(Composite parent, IWizardHandle handle) { wizardHandle = handle; handle.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry() .getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO)); Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); createKeyPairComposite(composite); createSSLCertControls(composite); createCNAMEControls(composite); createHealthCheckURLControls(composite); createQueueURLControls(composite); createSNSTopicControls(composite); newLabel(composite, ""); createIncrementalDeploymentControls(composite); bindControls(); initializeDefaults(); return composite; } private void createQueueURLControls(final Composite parent) { newLabel(parent, "Worker Queue URL"); workerQueueUrlText = newText(parent, ""); workerQueueUrlObservable = SWTObservables.observeText(workerQueueUrlText, SWT.Modify); } @Override public void enter() { String environmentType = wizardDataModel.getEnvironmentType(); // Health check isn't applicable for single-instance environments. if (ConfigurationOptionConstants.SINGLE_INSTANCE_ENV.equals(environmentType)) { healthCheckText.setText(""); healthCheckText.setEnabled(false); } else { healthCheckText.setEnabled(true); } // CName isn't applicable for worker environments; worker queue is. if (ConfigurationOptionConstants.WORKER_ENV.equals(environmentType)) { usingCnameButton.setSelection(false); usingCnameButton.setEnabled(false); cname.setText(""); cname.setEnabled(false); workerQueueUrlText.setEnabled(true); } else { usingCnameButton.setEnabled(true); cname.setEnabled(usingCnameButton.getSelection()); workerQueueUrlText.setText(""); workerQueueUrlText.setEnabled(false); } } private void createKeyPairComposite(Composite composite) { usingKeyPair = newCheckbox(composite, "Deploy with a key pair", 1); keyPairComposite = new KeyPairComposite(composite, AwsToolkitCore.getDefault().getCurrentAccountId(), wizardDataModel.getRegion()); wizardDataModel.setKeyPairComposite(keyPairComposite); usingKeyPair.addSelectionListener(new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } @Override public void widgetSelected(SelectionEvent e) { keyPairComposite.setEnabled(usingKeyPair.getSelection()); } }); GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false); layoutData.heightHint = 140; keyPairComposite.setLayoutData(layoutData); } private void createSSLCertControls(Composite composite) { newLabel(composite, "SSL certificate Id"); Text text = newText(composite, ""); sslCertObservable = SWTObservables.observeText(text, SWT.Modify); } private void createCNAMEControls(Composite composite) { usingCnameButton = newCheckbox(composite, "Assign CNAME prefix to new server", 1); cname = newText(composite); usingCnameButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { cname.setEnabled(usingCnameButton.getSelection()); } }); } private void createIncrementalDeploymentControls(Composite parent) { incrementalDeploymentButton = newCheckbox(parent, "Use incremental deployment", 1); incrementalDeploymentButton.setSelection(true); } private void createHealthCheckURLControls(Composite composite) { newLabel(composite, "Application health check URL"); healthCheckText = newText(composite, ""); healthCheckURLObservable = SWTObservables.observeText(healthCheckText, SWT.Modify); } private void createSNSTopicControls(Composite composite) { newLabel(composite, "Email address for notifications"); Text text = newText(composite, ""); snsTopicObservable = SWTObservables.observeText(text, SWT.Modify); } private void initializeDefaults() { usingCnameObservable.setValue(false); usingKeyPairObservable.setValue(false); keyPairComposite.setEnabled(false); cname.setEnabled(false); cname.setText(""); sslCertObservable.setValue(""); snsTopicObservable.setValue(""); healthCheckURLObservable.setValue(""); workerQueueUrlObservable.setValue(""); // No change event is necessarily fired from the above updates, so we // fire one manually in order to display the appropriate button enablement changeListener.handleChange(null); } /** * Creates validation bindings for the controls on this page. */ private void bindControls() { initializeValidators(); // Key pair usingKeyPairObservable = SWTObservables.observeSelection(usingKeyPair); bindingContext.bindValue(usingKeyPairObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.USING_KEY_PAIR), null, null); IViewerObservableValue keyPairSelectionObservable = ViewersObservables.observeSingleSelection(keyPairComposite .getViewer()); bindingContext.bindValue(keyPairSelectionObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.KEY_PAIR), null, null); ChainValidator<String> keyPairValidator = new ChainValidator<>(keyPairSelectionObservable, usingKeyPairObservable, new ValidKeyPairValidator(AwsToolkitCore.getDefault().getCurrentAccountId())); bindingContext.addValidationStatusProvider(keyPairValidator); usingCnameObservable = SWTObservables.observeSelection(usingCnameButton); bindingContext.bindValue(usingCnameObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.USING_CNAME), null, null) .updateTargetToModel(); bindingContext.bindValue(SWTObservables.observeText(cname, SWT.Modify), PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.CNAME), null, null) .updateTargetToModel(); // SSL cert bindingContext.bindValue(sslCertObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.SSL_CERTIFICATE_ID)); // CNAME // TODO: make CNAME conform to exact spec, check for in-use ChainValidator<String> chainValidator = new ChainValidator<>( SWTObservables.observeText(cname, SWT.Modify), usingCnameObservable, new NotEmptyValidator( "CNAME cannot be empty."), new NoInvalidNameCharactersValidator("Invalid characters in CNAME.")); bindingContext.addValidationStatusProvider(chainValidator); ControlDecoration cnameDecoration = newControlDecoration(cname, "Enter a CNAME to launch your server"); new DecorationChangeListener(cnameDecoration, chainValidator.getValidationStatus()); // Health check URL bindingContext.bindValue(healthCheckURLObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.HEALTH_CHECK_URL)); // SNS topic "email address" bindingContext.bindValue(snsTopicObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.SNS_ENDPOINT)); // Incremental deployment bindingContext.bindValue(SWTObservables.observeSelection(incrementalDeploymentButton), PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.INCREMENTAL_DEPLOYMENT)); // Worker Queue URL bindingContext.bindValue(workerQueueUrlObservable, PojoObservables.observeValue(wizardDataModel, DeployWizardDataModel.WORKER_QUEUE_URL)); } @Override public String getPageTitle() { return "Advanced configuration"; } @Override public String getPageDescription() { return "Specify advanced properties for your environment"; } }
7,385
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/AbstractDeployWizardPage.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui; import java.util.Iterator; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Text; import org.eclipse.wst.server.ui.wizard.IWizardHandle; import org.eclipse.wst.server.ui.wizard.WizardFragment; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.eclipse.elasticbeanstalk.deploy.DeployWizardDataModel; import com.amazonaws.eclipse.elasticbeanstalk.deploy.NotEmptyValidator; /** * Abstract base class with utilities common to all deploy wizard pages. */ public abstract class AbstractDeployWizardPage extends WizardFragment { @Override public boolean hasComposite() { return true; } protected DeployWizardDataModel wizardDataModel; /** Binding context for UI controls and deploy wizard data model */ protected DataBindingContext bindingContext; /** Collective status of all validators in our binding context */ protected AggregateValidationStatus aggregateValidationStatus; protected IWizardHandle wizardHandle; /** * Generic selection listener used by radio buttons created by this class to * notify the page to update controls and re-run binding validators. */ protected final SelectionListener selectionListener = new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } @Override public void widgetSelected(SelectionEvent e) { radioButtonSelected(e.getSource()); runValidators(); } }; /** * Initializes the data validators with a fresh state. Subclasses should * call this before performing data binding to ensure they don't have stale * handlers. Because these fragments persist in the workbench and the * objects are reused, this process must be performed somewhere in the * lifecycle other than the constructor. */ protected final void initializeValidators() { bindingContext = new DataBindingContext(); aggregateValidationStatus = new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY); } protected IChangeListener changeListener; /** * Subclasses can override this callback method to be notified when the value of a radio button * changes so that any additional UI updates can be made. */ protected void radioButtonSelected(Object sourceButton) { } protected AbstractDeployWizardPage(DeployWizardDataModel wizardDataModel) { this.wizardDataModel = wizardDataModel; changeListener = new IChangeListener() { @Override public void handleChange(ChangeEvent event) { Object value = aggregateValidationStatus.getValue(); if (value instanceof IStatus == false) return; wizardHandle.setMessage(getPageDescription(), IStatus.OK); IStatus status = (IStatus)value; setComplete(status.getSeverity() == IStatus.OK); } }; } /** * Returns the page title for this fragment. */ public abstract String getPageTitle(); /** * Returns the "OK" status message for this fragment. */ public abstract String getPageDescription(); @Override public void enter() { if (wizardHandle != null) { wizardHandle.setTitle(getPageTitle()); wizardHandle.setMessage(getPageDescription(), IStatus.OK); } if (aggregateValidationStatus != null) aggregateValidationStatus.addChangeListener(changeListener); } @Override public void exit() { if (aggregateValidationStatus != null) aggregateValidationStatus.removeChangeListener(changeListener); } @Override public void performCancel(IProgressMonitor monitor) throws CoreException { setComplete(false); exit(); } @Override public void performFinish(IProgressMonitor monitor) throws CoreException { setComplete(false); exit(); } /** * Runs all the validators for the current binding context. */ protected void runValidators() { Iterator<?> iterator = bindingContext.getBindings().iterator(); while (iterator.hasNext()) { Binding binding = (Binding)iterator.next(); binding.updateTargetToModel(); } } /* * Widget Helper Methods */ public static ControlDecoration newControlDecoration(Control control, String message) { ControlDecoration decoration = new ControlDecoration(control, SWT.LEFT | SWT.TOP); decoration.setDescriptionText(message); FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR); decoration.setImage(fieldDecoration.getImage()); return decoration; } public static Group newGroup(Composite parent, String text) { return newGroup(parent, text, 1); } public static Group newGroup(Composite parent, String text, int colspan) { Group group = new Group(parent, SWT.NONE); group.setText(text); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalSpan = colspan; group.setLayoutData(gridData); group.setLayout(new GridLayout(1, false)); return group; } public static Text newText(Composite parent) { return newText(parent, ""); } public static Text newText(Composite parent, String value) { Text text = new Text(parent, SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); text.setText(value); return text; } public static Label newLabel(Composite parent, String text) { return newLabel(parent, text, 1); } public static Label newFillingLabel(Composite parent, String text) { return newFillingLabel(parent, text, 1); } public static Label newFillingLabel(Composite parent, String text, int colspan) { Label label = new Label(parent, SWT.WRAP); label.setText(text); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalSpan = colspan; gridData.widthHint = 100; label.setLayoutData(gridData); return label; } public static Label newLabel(Composite parent, String text, int colspan) { Label label = new Label(parent, SWT.WRAP); label.setText(text); GridData gridData = new GridData(SWT.LEFT, SWT.TOP, false, false); gridData.horizontalSpan = colspan; label.setLayoutData(gridData); return label; } public static Label newLabel(Composite parent, String text, int colspan, int horizontalAlignment, int verticalAlignment) { Label label = new Label(parent, SWT.WRAP); label.setText(text); GridData gridData = new GridData(horizontalAlignment, verticalAlignment, false, false); gridData.horizontalSpan = colspan; label.setLayoutData(gridData); return label; } public static Link newLink(Composite composite, String message) { Link link = new Link(composite, SWT.WRAP); WebLinkListener webLinkListener = new WebLinkListener(); link.addListener(SWT.Selection, webLinkListener); link.setText(message); return link; } public static Combo newCombo(Composite parent) { return newCombo(parent, 1); } public static Combo newCombo(Composite parent, int colspan) { Combo combo = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = colspan; combo.setLayoutData(gridData); return combo; } public static Button newCheckbox(Composite parent, String text, int colspan) { Button button = new Button(parent, SWT.CHECK); button.setText(text); GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false); gridData.horizontalSpan = colspan; button.setLayoutData(gridData); return button; } public static UpdateValueStrategy newUpdateValueStrategy(ControlDecoration decoration, Button button) { UpdateValueStrategy strategy = new UpdateValueStrategy(); strategy.setAfterConvertValidator(new NotEmptyValidator(decoration, button)); return strategy; } protected Button newRadioButton(Composite parent, String text, int colspan) { return newRadioButton(parent, text, colspan, false); } protected Button newRadioButton(Composite parent, String text, int colspan, boolean selected) { return newRadioButton(parent, text, colspan, selected, selectionListener); } public static Button newRadioButton(Composite parent, String text, int colspan, boolean selected, SelectionListener selectionListener) { Button radioButton = new Button(parent, SWT.RADIO); radioButton.setText(text); GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false); gridData.horizontalSpan = colspan; radioButton.setLayoutData(gridData); radioButton.addSelectionListener(selectionListener); radioButton.setSelection(selected); return radioButton; } /** * Customize the link's layout data */ public void adjustLinkLayout(Link link, int colspan) { GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.widthHint = 200; gridData.horizontalSpan = colspan; link.setLayoutData(gridData); } }
7,386
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/databinding/ConfigurationSettingValidator.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.elasticbeanstalk.server.ui.databinding; import java.util.regex.Pattern; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription; /** * Validates a text-based config option */ public class ConfigurationSettingValidator implements IValidator { private ConfigurationOptionDescription configOption; public ConfigurationSettingValidator(ConfigurationOptionDescription configOption) { this.configOption = configOption; } @Override public IStatus validate(Object value) { String s = (String) value; if (s == null || s.length() == 0) { return ValidationStatus.ok(); } if ( configOption.getMaxValue() != null ) { try { Integer i = Integer.parseInt(s); if ( i > configOption.getMaxValue() ) { return ValidationStatus.error(configOption.getName() + " must be at most " + configOption.getMaxValue()); } } catch ( NumberFormatException e ) { return ValidationStatus.error(s + " isn't an integer (" + configOption.getNamespace() + ":" + configOption.getName() + ")"); } } if ( configOption.getMinValue() != null ) { try { Integer i = Integer.parseInt(s); if ( i < configOption.getMinValue() ) { return ValidationStatus.error(configOption.getName() + " must be at least " + configOption.getMinValue()); } } catch ( NumberFormatException e ) { return ValidationStatus.error(s + " isn't an integer (" + configOption.getNamespace() + ":" + configOption.getName() + ")"); } } if ( configOption.getMaxLength() != null ) { if ( s.length() > configOption.getMaxLength() ) { return ValidationStatus.error(s + " is too long (max length " + configOption.getMaxLength() + ")"); } } if ( configOption.getRegex() != null && s != null && s.length() > 0 ) { Pattern regex = Pattern.compile(configOption.getRegex().getPattern()); if ( !regex.matcher(s).matches() ) { return ValidationStatus.error(configOption.getName() + " must match the regular expression " + configOption.getRegex().getPattern()); } } return ValidationStatus.ok(); } }
7,387
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/databinding/RegexValidator.java
/* * Copyright 2015 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui.databinding; import java.util.regex.Pattern; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; /** * IValidator implementation that tests that a string matches the given regex */ public class RegexValidator implements IValidator { private final String message; private final String regex; public RegexValidator(String message, String regex) { this.message = message; this.regex = regex; } @Override public IStatus validate(Object value) { String s = (String)value; if (!Pattern.matches(regex, s)) return ValidationStatus.error(message); return ValidationStatus.ok(); } }
7,388
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/databinding/EnvironmentNameValidator.java
/* * Copyright 2015 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui.databinding; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.runtime.IStatus; /** * IValidator implementation that tests if the environment name matches the * specification in http://docs.aws.amazon.com/elasticbeanstalk/latest/api/ * API_CreateEnvironment.html. */ public class EnvironmentNameValidator implements IValidator { private static final String regex = "^[\\p{Alnum}]+[\\p{Alnum}-]+[\\p{Alnum}]$"; private static final int MIN_LENGTH = 4; private static final int MAX_LENGTH = 40; private final MinMaxLengthValidator lengthValidator = new MinMaxLengthValidator( "Environment Name", MIN_LENGTH, MAX_LENGTH); private final RegexValidator regexValidator = new RegexValidator( "Environment name can contain only letters, alphabets and hyphens and cannot start/end with an hyphen.", regex); @Override public IStatus validate(Object value) { IStatus status = lengthValidator.validate(value); if (status.getSeverity() == IStatus.OK) { status = regexValidator.validate(value); } return status; } }
7,389
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/databinding/ApplicationNameValidator.java
/* * Copyright 2015 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui.databinding; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; /** * IValidator implementation that tests if the application name matches the specification in * http://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_CreateEnvironment.html. */ public class ApplicationNameValidator implements IValidator { private static final int MIN_LENGTH = 1; private static final int MAX_LENGTH = 100; private static final MinMaxLengthValidator lengthValidator = new MinMaxLengthValidator("Application Name", MIN_LENGTH, MAX_LENGTH); @Override public IStatus validate(Object value) { IStatus status = lengthValidator.validate(value); final String s = (String)value; if (s.contains("/")) { return ValidationStatus.error("Application Name cannot contain a /"); } return status; } }
7,390
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/databinding/MinMaxLengthValidator.java
/* * Copyright 2015 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui.databinding; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import com.amazonaws.eclipse.core.validator.StringLengthValidator; /** * IValidator implementation that tests that a string for length constraints. * Excludes the range specified. * @deprecated to {@link StringLengthValidator} */ @Deprecated public class MinMaxLengthValidator implements IValidator { private final String message = "%s must be %d to %d characters in length."; private final int min; private final int max; private final String fieldName; public MinMaxLengthValidator(String fieldName, int min, int max) { this.min = min; this.max = max; this.fieldName = fieldName; } @Override public IStatus validate(Object value) { String s = (String)value; if (s.length() < min || s.length() > max) { return ValidationStatus.error(String.format(message, fieldName, min, max)); } return ValidationStatus.ok(); } }
7,391
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/databinding/NoInvalidNameCharactersValidator.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.elasticbeanstalk.server.ui.databinding; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; /** * IValidator implementation that tests that a string value doesn't contain any * invalid characters. */ public class NoInvalidNameCharactersValidator implements IValidator { public String message; public NoInvalidNameCharactersValidator(String message) { this.message = message; } @Override public IStatus validate(Object value) { String s = (String)value; if (s.contains(" ")) return ValidationStatus.info(message); return ValidationStatus.ok(); } }
7,392
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/ExportTemplateDialog.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.elasticbeanstalk.server.ui.configEditor; import java.util.Collection; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.databinding.observable.set.WritableSet; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.DecorationChangeListener; import com.amazonaws.eclipse.databinding.NotEmptyValidator; import com.amazonaws.eclipse.databinding.NotInListValidator; /** * Simple wizard to export an environment configuration template. */ public class ExportTemplateDialog extends MessageDialog { private String templateName; private Collection<String> existingTemplateNames; private DataBindingContext bindingContext = new DataBindingContext(); private IObservableValue isCreatingNew = new WritableValue(); private IObservableValue newTemplateName = new WritableValue(); private IObservableValue existingTemplateName = new WritableValue(); private IObservableValue templateDescription = new WritableValue(); private AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY); public boolean isCreatingNew() { return (Boolean) isCreatingNew.getValue(); } public String getTemplateDescription() { return (String) templateDescription.getValue(); } public String getTemplateName() { if ( isCreatingNew() ) { return (String) newTemplateName.getValue(); } else { return (String) existingTemplateName.getValue(); } } public ExportTemplateDialog(Shell parentShell, Collection<String> existingTemplateNames, String defaultTemplateName) { super(parentShell, "Export configuration template", null, "Choose a name and description for your template", MessageDialog.NONE, new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0); this.templateName = defaultTemplateName; this.existingTemplateNames = existingTemplateNames; } @Override protected Control createCustomArea(Composite parent) { parent.setLayout(new FillLayout()); Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); Group templateNameGroup = new Group(composite, SWT.None); templateNameGroup.setLayout(new GridLayout(2, false)); GridData groupData = new GridData(); groupData.horizontalSpan = 2; templateNameGroup.setLayoutData(groupData); // Update existing template final Button updateExistingRadioButton = new Button(templateNameGroup, SWT.RADIO); updateExistingRadioButton.setText("Update an existing template"); final Combo existingTemplateNamesCombo = new Combo(templateNameGroup, SWT.READ_ONLY); existingTemplateNamesCombo.setEnabled(false); if ( existingTemplateNames.isEmpty() ) { updateExistingRadioButton.setEnabled(false); } else { existingTemplateNamesCombo .setItems(existingTemplateNames.toArray(new String[existingTemplateNames.size()])); existingTemplateNamesCombo.select(0); } // Create new template -- default option Button createNewRadioButton = new Button(templateNameGroup, SWT.RADIO); createNewRadioButton.setText("Create a new template"); final Text templateNameText = new Text(templateNameGroup, SWT.BORDER); templateNameText.setText(templateName); templateNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); updateExistingRadioButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { templateNameText.setEnabled(!updateExistingRadioButton.getSelection()); existingTemplateNamesCombo.setEnabled(updateExistingRadioButton.getSelection()); } }); // Description new Label(composite, SWT.NONE).setText("Template description: "); final Text templateDescriptionText = new Text(composite, SWT.BORDER); templateDescriptionText.setText(""); templateDescriptionText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); // Data binding bindingContext.bindValue(SWTObservables.observeSelection(createNewRadioButton), isCreatingNew); isCreatingNew.setValue(true); bindingContext.bindValue(SWTObservables.observeSelection(existingTemplateNamesCombo), existingTemplateName) .updateTargetToModel(); bindingContext.bindValue(SWTObservables.observeText(templateNameText, SWT.Modify), newTemplateName); bindingContext.bindValue(SWTObservables.observeText(templateDescriptionText, SWT.Modify), templateDescription); WritableSet inUseNames = new WritableSet(); inUseNames.addAll(existingTemplateNames); ChainValidator<String> validator = new ChainValidator<>(newTemplateName, isCreatingNew, new NotEmptyValidator("Template name cannot be empty"), new NotInListValidator<String>(inUseNames, "Template name already in use")); bindingContext.addValidationStatusProvider(validator); // Decorate the new name field with error status ControlDecoration decoration = new ControlDecoration(templateNameText, SWT.TOP | SWT.LEFT); decoration.setDescriptionText("Invalid value"); FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration( FieldDecorationRegistry.DEC_ERROR); decoration.setImage(fieldDecoration.getImage()); new DecorationChangeListener(decoration, validator.getValidationStatus()); return composite; } /** * We need to add our button enabling listener here, because they haven't * been created yet in createCustomArea */ @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); aggregateValidationStatus.addChangeListener(new IChangeListener() { @Override public void handleChange(ChangeEvent event) { Object value = aggregateValidationStatus.getValue(); if ( value instanceof IStatus == false ) return; IStatus status = (IStatus) value; Button okButton = getButton(0); if ( okButton != null ) { if ( status.getSeverity() == IStatus.OK ) { okButton.setEnabled(true); } else { okButton.setEnabled(false); } } } }); getButton(0).setEnabled(false); } }
7,393
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/EventLogEditorSection.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor; import java.util.ArrayList; 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.core.runtime.jobs.Job; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.IServerListener; import org.eclipse.wst.server.core.ServerEvent; import org.eclipse.wst.server.ui.editor.ServerEditorSection; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin; import com.amazonaws.eclipse.elasticbeanstalk.Environment; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.model.DescribeEventsRequest; import com.amazonaws.services.elasticbeanstalk.model.EventDescription; import com.amazonaws.services.elasticbeanstalk.model.EventSeverity; /** * Editor part which displays the event log. */ public class EventLogEditorSection extends ServerEditorSection { /** The section widget we're managing */ private Section section; private FormToolkit toolkit; private TreeViewer viewer; private boolean tableDataLoaded = false; private static final Object JOB_FAMILY = new Object(); private AutoRefreshListener autoRefreshListener; private volatile boolean disposed; @Override public void createSection(Composite parent) { super.createSection(parent); toolkit = getFormToolkit(parent.getDisplay()); section = toolkit.createSection(parent, Section.TITLE_BAR | Section.DESCRIPTION ); section.setText("Environment Events"); section.setDescription("Events recorded to your Elastic Beanstalk environment"); Composite composite = toolkit.createComposite(section); FillLayout layout = new FillLayout(); layout.marginHeight = 10; layout.marginWidth = 10; layout.type = SWT.VERTICAL; composite.setLayout(layout); toolkit.paintBordersFor(composite); section.setClient(composite); section.setLayout(layout); createEventsTable(composite); configureAutoRefresh(); refresh(); } private void configureAutoRefresh() { autoRefreshListener = new AutoRefreshListener(); Environment environment = (Environment) server.loadAdapter(Environment.class, null); environment.getServer().addServerListener(autoRefreshListener); // Go ahead and start auto refreshing if the server is already // starting up, since we won't see the starting event if (environment.getServer().getServerState() == IServer.STATE_STARTING) { EventLogRefreshManager.getInstance().startAutoRefresh(this); } } protected TreeColumn newColumn(String columnText, int weight) { Tree table = viewer.getTree(); TreeColumn column = new TreeColumn(table, SWT.NONE); column.setText(columnText); TreeColumnLayout tableColumnLayout = (TreeColumnLayout) viewer.getTree().getParent().getLayout(); if ( tableColumnLayout == null ) { tableColumnLayout = new TreeColumnLayout(); } tableColumnLayout.setColumnData(column, new ColumnWeightData(weight)); return column; } private final class AutoRefreshListener implements IServerListener { @Override public void serverChanged(ServerEvent event) { if ((event.getKind() & ServerEvent.SERVER_CHANGE) == 0) { return; } switch (event.getState()) { case IServer.STATE_STARTING: EventLogRefreshManager.getInstance().startAutoRefresh(EventLogEditorSection.this); break; default: EventLogRefreshManager.getInstance().stopAutoRefresh(EventLogEditorSection.this); break; } } public void dispose() { EventLogRefreshManager.getInstance().stopAutoRefresh(EventLogEditorSection.this); } } /** Populates the Event Log context menu with actions. */ private final class EventLogMenuListener implements IMenuListener { private Action copyToClipboardAction = new Action("Copy to Clipboard") { @Override public ImageDescriptor getImageDescriptor() { return ElasticBeanstalkPlugin.getDefault().getImageRegistry().getDescriptor(ElasticBeanstalkPlugin.IMG_CLIPBOARD); } @Override public void run() { final Clipboard clipboard = new Clipboard(Display.getDefault()); String eventText = ""; for (TreeItem treeItem : viewer.getTree().getSelection()) { if (eventText == null) { eventText = treeItem.getData().toString(); } else { eventText += "\n" + treeItem.getData().toString(); } } TextTransfer textTransfer = TextTransfer.getInstance(); clipboard.setContents(new Object[]{eventText}, new Transfer[]{textTransfer}); } }; @Override public void menuAboutToShow(IMenuManager manager) { TreeItem[] selection = viewer.getTree().getSelection(); copyToClipboardAction.setEnabled(selection != null && selection.length > 0); manager.add(copyToClipboardAction); } } private class LoadEnvironmentEventsJob extends Job { private final Environment environment; public LoadEnvironmentEventsJob(Environment environment) { super("Loading events for environment " + environment.getEnvironmentName()); this.environment = environment; this.setSystem(true); } @Override protected IStatus run(IProgressMonitor monitor) { AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId()) .getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint()); final List<EventDescription> events = client.describeEvents(new DescribeEventsRequest() .withEnvironmentName(environment.getEnvironmentName())).getEvents(); Display.getDefault().syncExec(new Runnable() { @Override public void run() { if (disposed || viewer.getTree().isDisposed()) { return; } // Preserve the current column widths int[] colWidth = new int[viewer.getTree().getColumns().length]; int i = 0; for (TreeColumn col : viewer.getTree().getColumns()) { colWidth[i++] = col.getWidth(); } viewer.setInput(events); // If this is the first time loading the table data, don't // set the column widths -- this will make them zero on // windows. if ( tableDataLoaded ) { i = 0; for ( TreeColumn col : viewer.getTree().getColumns() ) { col.setWidth(colWidth[i++]); } } else { tableDataLoaded = true; } } }); return Status.OK_STATUS; } @Override public boolean belongsTo(Object family) { return family == JOB_FAMILY; } } private void addContextMenu() { MenuManager menuManager = new MenuManager("#PopupMenu"); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new EventLogMenuListener()); Menu menu = menuManager.createContextMenu(viewer.getControl()); viewer.getControl().setMenu(menu); } private void createEventsTable(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); TreeColumnLayout treeColumnLayout = new TreeColumnLayout(); composite.setLayout(treeColumnLayout); int style = SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI; viewer = new TreeViewer(composite, style); viewer.getTree().setLinesVisible(true); viewer.getTree().setHeaderVisible(true); addContextMenu(); newColumn("Message", 75); newColumn("Version", 10); newColumn("Date", 15); viewer.setContentProvider(new ITreeContentProvider() { private List<EventDescription> events; @Override @SuppressWarnings("unchecked") public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput == null) { events = new ArrayList<>(); } else { events = (List<EventDescription>)newInput; } } @Override public void dispose() { } @Override public Object[] getElements(Object inputElement) { return events.toArray(); } @Override public Object[] getChildren(Object parentElement) { return new Object[0]; } @Override public Object getParent(Object element) { return null; } @Override public boolean hasChildren(Object element) { return false; } }); viewer.setLabelProvider(new ITableLabelProvider() { @Override public void removeListener(ILabelProviderListener listener) { } @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public void dispose() { } @Override public void addListener(ILabelProviderListener listener) { } @Override public String getColumnText(Object element, int columnIndex) { EventDescription event = (EventDescription) element; switch (columnIndex) { case 0: return event.getMessage(); case 1: return event.getVersionLabel(); case 2: return event.getEventDate().toString(); default: return ""; } } @Override public Image getColumnImage(Object element, int columnIndex) { if (element == null) { return null; } if (columnIndex != 0) { return null; } EventSeverity eventSeverity = null; try { EventDescription event = (EventDescription)element; eventSeverity = EventSeverity.fromValue(event.getSeverity()); } catch (IllegalArgumentException e) { return null; } switch (eventSeverity) { case ERROR: case FATAL: return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK); case WARN: return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_WARN_TSK); case INFO: case DEBUG: case TRACE: return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_INFO_TSK); } return null; } }); } @Override public void dispose() { disposed = true; if (autoRefreshListener != null) { Environment environment = (Environment) server.loadAdapter(Environment.class, null); environment.getServer().removeServerListener(autoRefreshListener); autoRefreshListener.dispose(); } super.dispose(); } public String getServerName() { return server.getName(); } /** * Refreshes the events in the table. */ void refresh() { /* * There's a race condition here, but the consequences are trivial. */ if ( Job.getJobManager().find(JOB_FAMILY).length == 0 ) { Environment environment = (Environment) server.loadAdapter(Environment.class, null); new LoadEnvironmentEventsJob(environment).schedule(); } } }
7,394
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/EnvironmentConfigEditorSection.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor; import java.util.ArrayList; import java.util.List; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateSetStrategy; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.databinding.observable.set.IObservableSet; import org.eclipse.core.databinding.observable.set.ISetChangeListener; import org.eclipse.core.databinding.observable.set.SetChangeEvent; import org.eclipse.core.databinding.observable.set.WritableSet; import org.eclipse.core.databinding.observable.value.IObservableValue; 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.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.wst.server.ui.editor.ServerEditorSection; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.DecorationChangeListener; import com.amazonaws.eclipse.elasticbeanstalk.Environment; import com.amazonaws.eclipse.elasticbeanstalk.server.ui.databinding.ConfigurationSettingValidator; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription; /** * Abstract base editor section that knows how to create controls for an editable option. */ public class EnvironmentConfigEditorSection extends ServerEditorSection { /** The section widget we're managing */ protected Section section; protected AbstractEnvironmentConfigEditorPart parentEditor; protected EnvironmentConfigDataModel model; protected DataBindingContext bindingContext; protected final Environment environment; protected FormToolkit toolkit; protected String namespace; protected List<ConfigurationOptionDescription> options; /** * Sets the list of options that this section will present to the user, one * control per option. Can be set any time before the page is constructed. */ public void setOptions(List<ConfigurationOptionDescription> options) { this.options = options; } /** * Constructs a new section for one namespace. * * @param parentEditor * The editorPart that created this section * @param namespace * The namespace of this section * @param options * The options in the namespace */ public EnvironmentConfigEditorSection(AbstractEnvironmentConfigEditorPart parentEditor, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext, String namespace, List<ConfigurationOptionDescription> options) { this.parentEditor = parentEditor; this.bindingContext = bindingContext; this.environment = environment; this.model = model; this.namespace = namespace; this.options = options; } public int getNumControls() { return options.size(); } @Override public void createSection(Composite parent) { super.createSection(parent); toolkit = getFormToolkit(parent.getDisplay()); section = getSection(parent); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, false); section.setLayoutData(layoutData); Composite composite = toolkit.createComposite(section); GridLayout layout = new GridLayout(2, false); layout.marginHeight = 5; layout.marginWidth = 10; layout.verticalSpacing = 10; layout.horizontalSpacing = 15; composite.setLayout(layout); composite.setLayoutData(layoutData); toolkit.paintBordersFor(composite); section.setClient(composite); section.setLayout(layout); section.setLayoutData(layoutData); createSectionControls(composite); section.setDescription(getSectionDescription()); section.setText(getSectionName()); } /** * Creates a section in the given composite. */ protected Section getSection(Composite parent) { return toolkit.createSection(parent, ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR | ExpandableComposite.FOCUS_TITLE); } /** * Creates all controls for the page using the composite given. */ protected void createSectionControls(Composite composite) { for ( ConfigurationOptionDescription o : options ) { createOptionControl(composite, o); } } /** * Returns the name of this editor section. */ protected String getSectionName() { return namespace; } /** * Returns the description for this editor section. */ protected String getSectionDescription() { return null; } /** * Creates the appropriate control to display and change the option given. */ protected void createOptionControl(Composite parent, ConfigurationOptionDescription option) { String valueType = option.getValueType(); if ( valueType.equals("Scalar") ) { if (option.getValueOptions().isEmpty()) { createTextField(parent, option); } else { createCombo(parent, option); } } else if ( valueType.equals("Boolean") ) { createCheckbox(parent, option); } else if ( valueType.equals("List") ) { if (option.getValueOptions().isEmpty()) { createTextField(parent, option); } else { createList(parent, option); } } else if ( valueType.equals("CommaSeparatedList")) { createCommaSeparatedList(parent, option); } else if (valueType.equals("KeyValueList")) { createKeyValueList(parent, option); } else { Label label = createLabel(toolkit, parent, option); label.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); Label label1 = toolkit.createLabel(parent, (option.getValueOptions().toString() + "(" + valueType + ")")); label1.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); } } /** * Creates a key value list control with the option given */ private void createKeyValueList(Composite parent, ConfigurationOptionDescription option) { createTextField(parent, option); } /** * Creates a comma separated list with the option given */ private void createCommaSeparatedList(Composite parent, ConfigurationOptionDescription option) { createTextField(parent, option); } /** * Creates a list of checkable options with the option given. */ protected void createList(Composite parent, ConfigurationOptionDescription option) { GridData labelData = new GridData(SWT.LEFT, SWT.TOP, false, false); labelData.horizontalSpan = 2; Label label = createLabel(toolkit, parent, option); label.setLayoutData(labelData); /* * This process is complicated and differs from the rest of the * mutliple-view data model binding in that it doesn't use the data * model singleton as a proxy to generate an observable. This is because * the observable set of values is created when the model is. * * It also requires explicit two-way wiring via listeners: one chunk to * update the model when the controls change, and another to update the * controls when the model changes. One-way listening is sufficient to * update the model, but not to make the two views of the model align. */ final IObservableSet modelValues = (IObservableSet) model.getEntry(option); final IObservableSet controlValues = new WritableSet(); controlValues.addAll(modelValues); final List<Button> checkboxButtons = new ArrayList<>(); int i = 0; Button lastButton = null; /* * Each button needs a listener to update the observed set of model * values. */ for ( final String valueOption : option.getValueOptions() ) { final Button button = toolkit.createButton(parent, valueOption, SWT.CHECK); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (button.getSelection()) { controlValues.add(valueOption); } else { controlValues.remove(valueOption); } } }); button.addSelectionListener(new DirtyMarker()); checkboxButtons.add(button); lastButton = button; i++; } /* * Make sure we don't have an odd number of elements screwing up the * rest of the layout. */ if ( i % 2 != 0 ) { GridData buttonData = new GridData(SWT.LEFT, SWT.TOP, false, false); buttonData.horizontalSpan = 2; lastButton.setLayoutData(labelData); } Binding bindSet = bindingContext.bindSet(controlValues, modelValues, new UpdateSetStrategy(UpdateSetStrategy.POLICY_UPDATE), new UpdateSetStrategy(UpdateSetStrategy.POLICY_UPDATE)); /* * The observed set of model values needs a listener to update the * controls, in case the selection event came from another set of * controls with which we need to synchronize. */ controlValues.addSetChangeListener(new ISetChangeListener() { @Override public void handleSetChange(SetChangeEvent event) { for ( Button button : checkboxButtons ) { boolean checked = false; for ( Object value : modelValues ) { if (button.getText().equals(value)) { checked = true; break; } } button.setSelection(checked); } } }); bindSet.updateModelToTarget(); } /** * Creates a checkbox control with the option given. */ protected void createCheckbox(Composite parent, ConfigurationOptionDescription option) { Button button = toolkit.createButton(parent, getName(option), SWT.CHECK); GridData layoutData = new GridData(); layoutData.horizontalSpan = 2; button.setLayoutData(layoutData); IObservableValue modelv = model.observeEntry(option); ISWTObservableValue widget = SWTObservables.observeSelection(button); bindingContext.bindValue(widget, modelv, new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE), new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE)); modelv.addChangeListener(new DirtyMarker()); } protected String getName(ConfigurationOptionDescription option) { return option.getName(); } /** * Creates a drop-down combo with the option given. */ protected void createCombo(Composite parent, ConfigurationOptionDescription option) { Label label = createLabel(toolkit, parent, option); label.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); Combo combo = new Combo(parent, SWT.READ_ONLY); combo.setItems(option.getValueOptions().toArray(new String[option.getValueOptions().size()])); IObservableValue modelv = model.observeEntry(option); ISWTObservableValue widget = SWTObservables.observeSelection(combo); parentEditor.bindingContext.bindValue(widget, modelv, new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE), new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE)); modelv.addChangeListener(new DirtyMarker()); } /** * Creates a text field and label combo using the option given. */ protected void createTextField(Composite parent, ConfigurationOptionDescription option) { Label label = createLabel(toolkit, parent, option); label.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); Text text = toolkit.createText(parent, ""); layoutTextField(text); IObservableValue modelv = model.observeEntry(option); ISWTObservableValue widget = SWTObservables.observeText(text, SWT.Modify); bindingContext.bindValue(widget, modelv, new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE), new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE)); modelv.addChangeListener(new DirtyMarker()); ChainValidator<String> validationStatusProvider = new ChainValidator<>(widget, new ConfigurationSettingValidator(option)); bindingContext.addValidationStatusProvider(validationStatusProvider); ControlDecoration decoration = new ControlDecoration(text, 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()); } protected void layoutTextField(Text text) { GridData textLayout = new GridData(SWT.LEFT, SWT.TOP, false, false); GC gc = new GC(text); FontMetrics fm = gc.getFontMetrics(); textLayout.widthHint = text.computeSize(fm.getAverageCharWidth() * 30, SWT.DEFAULT).x; gc.dispose(); text.setLayoutData(textLayout); } protected Label createLabel(FormToolkit toolkit, Composite parent, ConfigurationOptionDescription option) { String labelText = getName(option); if ( option.getChangeSeverity().equals("RestartEnvironment") ) labelText += " **"; else if ( option.getChangeSeverity().equals("RestartApplicationServer") ) labelText += " *"; if ( option.getValueType().equals("CommaSeparatedList") && option.getValueOptions().isEmpty() ) { labelText += "\n(comma separated)"; } else if ( option.getValueType().equals("KeyValueList") && option.getValueOptions().isEmpty() ) { labelText += "\n(key-value list)"; } Label label = toolkit.createLabel(parent, labelText); return label; } /** * Generic listener that marks the editor dirty. */ protected final class DirtyMarker implements SelectionListener, ModifyListener, IChangeListener { public DirtyMarker() { } @Override public void modifyText(ModifyEvent e) { markDirty(); } @Override public void widgetSelected(SelectionEvent e) { markDirty(); } @Override public void widgetDefaultSelected(SelectionEvent e) { markDirty(); } private void markDirty() { EnvironmentConfigEditorSection.this.parentEditor.markDirty(); } @Override public void handleChange(ChangeEvent event) { markDirty(); } } }
7,395
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/EventLogRefreshManager.java
/* * Copyright 2013 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.elasticbeanstalk.server.ui.configEditor; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Keeps track of event logs for environments with active deployments in * progress and periodically refreshes them. */ public class EventLogRefreshManager { private final static EventLogRefreshManager instance = new EventLogRefreshManager(); private final ScheduledThreadPoolExecutor executor; private Set<EventLogEditorSection> activeEventLogs = new CopyOnWriteArraySet<>(); private EventLogRefreshManager() { executor = new ScheduledThreadPoolExecutor(1); executor.scheduleAtFixedRate(new EventLogRefresher(), 0, 30, TimeUnit.SECONDS); } private class EventLogRefresher implements Runnable { @Override public void run() { for (EventLogEditorSection eventLog : activeEventLogs) { eventLog.refresh(); } } } public static EventLogRefreshManager getInstance() { return instance; } public void startAutoRefresh(EventLogEditorSection eventLog) { activeEventLogs.add(eventLog); } public void stopAutoRefresh(EventLogEditorSection eventLog) { // Refresh one more time before we stop auto-refreshing, // to ensure that we don't miss the last events eventLog.refresh(); activeEventLogs.remove(eventLog); } }
7,396
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/DeploymentConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.wst.server.ui.editor.ServerEditorSection; import com.amazonaws.eclipse.elasticbeanstalk.Environment; public class DeploymentConfigEditorSection extends ServerEditorSection { @Override public void createSection(Composite parent) { super.createSection(parent); FormToolkit toolkit = getFormToolkit(parent.getDisplay()); String description = "Incremental deployment publishes only the changes in your project since your last deployment, which means faster deployments."; Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR | Section.DESCRIPTION | ExpandableComposite.FOCUS_TITLE); section.setText("AWS Elastic Beanstalk Deployment"); section.setDescription(description); section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL)); Composite composite = toolkit.createComposite(section); GridLayout layout = new GridLayout(); layout.marginHeight = 8; layout.marginWidth = 8; composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.FILL_HORIZONTAL)); toolkit.paintBordersFor(composite); section.setClient(composite); final Button incrementalDeploymentCheckbox = toolkit.createButton(composite, "Use Incremental Deployments", SWT.CHECK); final Environment environment = (Environment)server.getAdapter(Environment.class); incrementalDeploymentCheckbox.setSelection(environment.getIncrementalDeployment()); incrementalDeploymentCheckbox.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { execute(new AbstractOperation("Incremental Deployments") { private boolean originalState; @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { environment.setIncrementalDeployment(originalState); incrementalDeploymentCheckbox.setSelection(originalState); return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { environment.setIncrementalDeployment(!originalState); incrementalDeploymentCheckbox.setSelection(!originalState); return Status.OK_STATUS; } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { originalState = environment.getIncrementalDeployment(); environment.setIncrementalDeployment(incrementalDeploymentCheckbox.getSelection()); return Status.OK_STATUS; } }); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); } }
7,397
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/BeanstalkHealthColorConverter.java
/* * Copyright 2015 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor; import java.util.Map; import org.eclipse.jface.resource.ResourceManager; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import com.amazonaws.util.ImmutableMapParameter; /** * Helper class to convert from the String color name returned by the Beanstalk API to a * {@link Color} object usable in the UI */ public class BeanstalkHealthColorConverter { /** * Default color (Black) to return for any unknown colors returned by the service */ private static final RGB UNKNOWN = new RGB(0, 0, 0); private final ResourceManager resourceManager; //@formatter:off private final Map<String, RGB> colorNameToRgb = new ImmutableMapParameter.Builder<String, RGB>() .put("Green", new RGB(0, 150, 0)) .put("Yellow", new RGB(204, 204, 0)) .put("Red", new RGB(255, 0, 0)) .put("Grey", new RGB(96, 96, 96)) .build(); //@formatter:on public BeanstalkHealthColorConverter(ResourceManager resourceManager) { this.resourceManager = resourceManager; } /** * Convert the string representation of the color (as returned by the ElasticBeanstalk API) to a * SWF Color object * * @param healthColorName * Name of color returned by Beanstalk * @return Appropriate SWF Color or a default to handle new colors added by the service */ public Color toColor(String healthColorName) { return resourceManager.createColor(stringColorNameToRgb(healthColorName)); } /** * Convert the string representation of the color to an RGB object * * @param healthColorName * Name of color returned by Beanstalk * @return Appropriate RGB Color or a default to handle new colors added by the service */ private RGB stringColorNameToRgb(String healthColorName) { if (colorNameToRgb.containsKey(healthColorName)) { return colorNameToRgb.get(healthColorName); } return UNKNOWN; } }
7,398
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/LogTailEditorPart.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.forms.ManagedForm; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.wst.server.ui.editor.ServerEditorPart; import org.eclipse.wst.server.ui.internal.ImageResource; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.ec2.Ec2Plugin; import com.amazonaws.eclipse.explorer.AwsAction; public class LogTailEditorPart extends ServerEditorPart { private ManagedForm managedForm; @Override public void createPartControl(Composite parent) { managedForm = new ManagedForm(parent); setManagedForm(managedForm); ScrolledForm form = managedForm.getForm(); FormToolkit toolkit = managedForm.getToolkit(); toolkit.decorateFormHeading(form.getForm()); form.setText("Logs"); form.setImage(ImageResource.getImage(ImageResource.IMG_SERVER)); Composite columnComp = toolkit.createComposite(form.getBody()); FillLayout layout = new FillLayout(); layout.marginHeight = 0; columnComp.setLayout(new FillLayout()); form.getBody().setLayout(layout); final LogTailEditorSection editorSection = new LogTailEditorSection(); editorSection.setServerEditorPart(this); editorSection.init(this.getEditorSite(), this.getEditorInput()); editorSection.createSection(columnComp); managedForm.getForm().getToolBarManager().add(new AwsAction( AwsToolkitMetricType.EXPLORER_BEANSTALK_REFRESH_ENVIRONMENT_EDITOR, "Refresh", SWT.None) { @Override public ImageDescriptor getImageDescriptor() { return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh"); } @Override protected void doRun() { editorSection.refresh(); actionFinished(); } }); managedForm.getForm().getToolBarManager().update(true); form.reflow(true); } @Override public void setFocus() { managedForm.setFocus(); } }
7,399